Pointers
A pointer holds the memory address of an object. For a type T, T* is the type "pointer to T". For example,
int i = 5; int* ptr_to_i = &i; // ptr_to_i holds the address of i int *also_ptr_to_i = ptr_to_i;
The type of ptr_to_i is int*. Prefix unary & is the "address of" operator.
It is preferable to write
int *p;
rather than
int* p;
This is because in the following example:
int* p1, p2; // whoops, p2 is not a pointer-to-int
p1 is a pointer-to-int while p2 is a plain int. To make both variables pointers, we write this:
int *p1, *p2; // p1 and p2 are pointer-to-int
Dereferencing
The fundamental operation on a pointer is dereferencing. When you dereference a pointer, you get the object that the pointer is "pointing to". The dereferencing operator is prefix unary *. For example:
char c = 'w'; // c has the value 'w' char *ptr_to_c = &c; // ptr_to_c holds the address of c char c2 = *ptr_to_c; // dereference---c2 has the value 'w'
By dereferencing a pointer, we can change the value of the object pointed to:
char c = 'x'; char *ptr_to_c = &c; *ptr_to_c = 'y'; // c now has the value 'y'
Null Pointer
A pointer with the value zero (0) is a pointer that points to nothing. You must check that a pointer is not a NULL pointer before using it. Consider a function that takes a pointer as an argument:
void someFunction(int *p) { if( p ) { // p is not NULL---ok to use it here } else { // p is NULL---don't use p as is } }
Pointers and const
You should read pointer declarations from right to left. For example:
int *p; p is a pointer to an int.
const int *p; p is a pointer to a const int. The const int object cannot be changed via the pointer.
int *const p; p is a const pointer to an int. The int object can be changed by the pointer, but the pointer itself cannot be changed.
const int *const p; p is a const pointer to a const int. The const int object cannot be changed by the pointer, and the pointer itself cannot be changed.
The following example is from Stroustrup:
void f1(char *p) { char s[] = "Gorm"; const char *pc = s; // pointer to constant pc[3] = 'g'; // error: pc points to constant pc = p; // ok char *const cp = s; // constant pointer cp[3] = 'a'; // ok cp = p; // error: cp is constant const char *const cpc = s; // const pointer to const cpc[3] = 'a'; // error: cpc points to constant cpc = p; // error: cpc is constant }