Pointers in C++

1. Addresses in memory are essentially numbers that can be stored in (unsigned) integer variables. In my computer, it showed up as hexadecimals such as “0xbfb3a7b4”;

2. Pointer should be considered “a data type that holds an address of some variable”. A pointer variable is declared as “float*”, “char*”, etc.. “float*” holds a variable of “a type of float pointer” and “char*” holds a variable of “a type of char pointer” (which means it stores an address of a char variable). A primary motivation for having a pointer type for each variable type is to help the compiler. See “Pointer Arithmetic” section in this tutorial;

3. Two distinct steps when you try to access the value of a variable. First is to & (find the address in memory) and second is to *(retrieve the value from the address(es));

4. None pointer type can be cast to pointer type and vice versa. Since Pointer is a special type of object, it can be used to cast other types of object to the pointer type of choice. The following example casts type of unsigned integer to float pointer before retrieving its value and casts a pointer to unsigned integer.

float fl=3.14;
unsigned int addr=(unsigned int) &fl;
*(float*) addr = 12.34567;
int* flPtr = (int*) &fl;
unsigned int addr2 = (unsigned int) flPtr;
std::cout << fl <<” “<< &fl<< ” “<<flPtr<< ” “<<addr2<<std::endl;

5. An Array variable is actually already a pointer. It stores the address of the first object in the array; Accessing the array (*arr) is actually accessing the first element in the array (arr[0]):

int arr3[3] = {19, 39, 59};
int* b = arr3;
std::cout<<b<<“==? “<<&arr[0]<<std::endl;
std::cout<<b<<” ==? “<<arr3<<” ==? “<<&arr3[0]<<std::endl;
std::cout<<*arr3<<” ==? “<<arr[0]<<std::endl;
cout<< *(arr3+1)<<” ==? “<<arr3[1]<<endl;

6. Pointer arithmetic for accessing array /array elements. Use “*(people+1)” to access the second element in Array people (The followings are all true:


C++ compiler does not prevent pointer index falling out of range (nor does it complain when this happens). For “int people[5]”, *(people+5) will print out some none sense (the code will compile and run!).

Pionters in C and C++;

Array in C and C++;

and an interesting code discussion about “Pointer to array”



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: