C/C++‎ > ‎


In C/C++ (&), reference operator, means "address of" and asterisk (*), dereference operator, means "value pointed by".

so the following places the address of variable b into the pointer a.

int *a; // this is how you declare a pointer - the pointer needs to know what it's pointing to, thus we have to declare it using a type (int in this case)
a = &b;

This will put value 20 in variable b (since we pointer pointer a to b's location in memory above)

*a = 20;

In C/C++ an array is basically a pointer but its value can't be changed (its a constant pointer).

The following is valid

int myArray[20];
int *myPointer;
myPointer = myArray;

These two expressions are equivalent.

myPointer[5] = 0;
*(myPointer + 5) = 0;

Notes about pointer arithmetic:
You can only add or subtract when dealing with pointers. Note that
  • *myPointer++ is equivalent to *(myPointer++) because ++ has greater precedence over *. So *myPointer++ just points to the next element of myPointer, like myPointer[1].
  • (*myPointer)++ actually adds one to the value where myPointer is pointing to.

Pointers to Pointers

In here c is of the type char** and it points to value 'z'.

char a;
char * b;
char ** c;
a = 'z';
b = &a;
c = &b;

Void Pointers

Void pointers are pointers that don't have a type. They can point to any data type but this come at the price of not being able to dereference and get the value they are pointing to (since they don't know how long the value is). The only way to dereference is to use a cast to a specific type. These pointers are normally used to pass things to functions.

void myFunction(void *data, int size) { .... }

Null Pointers

Pointers that point to address 0 (integer) are said to not hold a special value and are Null Pointers.

int * p; p = 0; // p has a null pointer value

Pointers to Functions

C++ allows pointer to functions. This is useful to pass a function to another function.
Here the mFuncPointer was declared as a function pointer that takes 2 ints as arguments and return of type int. And it is immediately pointed to function mFunc.

int (* mFuncPointer)(int,int) = mFunc;

When you have a pointer to an object, calling a function would require dereferencing. The following are equivalent