Static arrays vs pointers

  1. Courses


  2. Complete C++ Course


  3. The basics


  4. Static arrays vs pointers

Static arrays

If we output a static array to the console, like in the following code:

int array[] = {0, 1, 2, 3}; std::cout << array << std::endl;

The result will be that the address of the array (Which is the address of its first element) will be written (In hexadecimal) in the console (Example: 0x60fe10). That means that the value of a static array is the memory address of the array. Printing a pointer to the console would have the same result. Are static arrays pointers?

Pointers to a static array

We make a pointer point to a static array without using the ampersand &. With a variable, the ampersand & before its name has the effect to return its memory address. We saw, earlier, that when we access a static array directly without brackets [], what we get is its address, so we do not need the ampersand to retrieve it. Example:

int array[] = {0, 1, 2, 3, 4}; int * ptr = array;

Now we could access the first element of the array array, through the pointer ptr, like that:

*ptr = 5;

But it is also possible to use pointers like static arrays, so the following works:

ptr[4] = 8; // The fifth element of array is assigned with the value 8.

Pointers to a multidimensional static array

To define a pointer to a multidimensional array, we must put the asterisk * and the name of the pointer inside parentheses and follow them by the sizes of the dimensions between brackets [], except for the first dimension:

int array[5][4][3]; int (*ptr)[4][3] = array;

The following line would have, instead, defined a 4x3 array of int pointers:

int *ptr[4][3]; ptr[0][0] = 0; // Set the first pointer to the address 0.

We can now access the elements of the multidimensional static array through the pointer ptr exactly as we would do with the array:

ptr[0][2][1] = 5; // The element (0, 2, 1) of array now equals 5.

Pointers vs static array

So, are static arrays pointers? Pointers and static arrays are used similarly, but they are not the same. A pointer is a variable that stores an address (a number). We then can use that address to refer to variables stored in the memory. A static array is simply a range of bytes, in the memory, that has been reserved by the compiler. We can use the name of the array to retrieve its address, however, we can not change it since its address is not actually written in the memory, because the array is not a variable that stores an address, it IS an address.