C++ pointer
In C++ pointer can store a memory address, normally it is a memory address of another variable or a result of new
operator. The size of a pointer depends upon the computer architecture.
Pointer does not have its own type name, but rather it uses the name of data that it points to with the symbol * before the name of the variable that stores the pointer. For example int a;
is an int, int *a;
is a pointer to int, int **a;
is a pointer to a pointer to int. It is possible to put a space between * and name as int * a;
, and to remove a space between type of data the pointer will point to and * as int* a;
; unfortunately this causes confusion when people think that it means that int*
defines a pointer to int, however, int* a, b;
will cause a to be a pointer to an integer, and b will be an integer variable.
Contents |
Getting address
To get an address to store into a pointer one needs to prepend the name of the variable with &. The operator new
, that creates new storage at the run time, also returns the pointer to the created space.
int *a; int b; a = &b; a = new int;
Constant and pointer
The confusing case when declaring pointers is differentiating between a constant pointer to data and a pointer to constant data.
const int * a; // pointer to const int int const * a; // pointer to const int int * const a; // const pointer to int const int * const a; // const pointer to const int int const * const a; // const pointer to const int const int const * a; // ERROR const int const * const a; // ERROR
Null pointer
Null pointer is a pointer to any data type which points to the non-existing value. Originally this value was written as null
, 0
, or '\0'
, however, from C++11 it should be written as nullptr. It is equivalent of (void*)0
after going through reinterpret_cast
.
Void pointer
Void pointer is the pointer to some address in memory, without explicit statement of what the data it is pointing to. Because of this it becomes impossible to work with that data (since compiler cannot know the size of the data, and won't even know how many bytes to get at that address). Void pointer is declared as void *
.
They are very rarely used in high-level C++ applications, but when they are used casting them to a pointer of a different type is needed before they can be dereferenced and used.
Pointer to an array
A pointer to an array is indistinguishable to a pointer to the first element of that array. Arithmetic can be used to move between elements of the array, square brackets work as well.
int *a, *b; // 2 pointers int ar_a[5]{0}, ar_b[5]{0}; // 2 arrays a = ar_a; b = &(ar_b[0]); a++; b+=1; (*a) = 3; b[0] = 3; a[2] = 5; *(b+2) = 5;
Here the exact same thing was happening to both arrays.