difference between pointer to an array and pointer to the first element of an array

Theory

First off some theory (you can skip to the “Answers” section but I suggest you to read this as well):

int arr[5]

this is an array and “arr” is not the pointer to the first element of the array. Under specific circumstances (i.e. passing them as lvalues to a function) they decay into pointers: you lose the ability of calling sizeof on them.

Under normal circumstances an array is an array and a pointer is a pointer and they’re two totally different things.

When dealing with a decayed pointer and the pointer to the array you wrote, they behave exactly the same but there’s a caveat: an array of type T can decay into a pointer of type T, but only once (or one level-deep). The newly created decayed type cannot further decay into anything else.

This means that a bidimensional array like

int array1[2][2] = {{0, 1}, {2, 3}};

can’t be passed to

void function1(int **a);

because it would imply a two-levels decaying and that’s not allowed (you lose how elements of the array are laid out). The followings would instead work:

void function1(int a[][2]);
void function1(int a[2][2]);

In the case of a 1-dimensional array passed as lvalue to a function you can have it decayed into a simple pointer and in that case you can use it as you would with any other pointer.


Answers

Answering your questions:

int (*arr)[5]

this is a pointer to an array and you can think of the “being an array of 5 integers” as being its type, i.e. you can’t use it to point to an array of 3 integers.

int arr[5]

this is an array and will always behave as an array except when you pass it as an lvalue

int* ptrToArr = arr;

in that case the array decays (with all the exceptions above I cited) and you get a pointer and you can use it as you want.

And: no, they’re not equal otherwise something like this would be allowed

int (*arr)[5]
int* ptrToArr = arr; // NOT ALLOWED

Error cannot convert ‘int (*)[5]’ to ‘int*’ in initialization

they’re both pointers but the difference is in their type.

Leave a Comment