Like many other developers, you are confused by decay. The following code is valid, because a
will implicitly decay to a pointer:
int a[] = {1,2,3};
int* b = a;
Decay is what notably allows arrays to implicitly transform into pointers to their first elements.
However, the following code is not valid, because decay is not the same as taking the address of the array:
int a[] = {1,2,3};
int* b = &a; // INVALID
The first example gets you a pointer to an integer (the first integer in the array). In the second example, &a
gets you a pointer to an array of 3 integers. If you had to assign it to a variable, its type would be:
int a[] = {1,2,3};
int (*b)[3] = &a;
The alien form should show you that this is not what you expect at all.
It is true that a
(once decayed), &a
and &a[0]
should all point to the same address. However, they do not point to the same kind of thing (&a
points to an array, while the others point to integers).
The result of pointer operations depend at least as much on the type of the pointer as to the value of the pointer. Each time you increase that &a
pointer by 1, you move by three integers in memory, not just one, because the size of the type is (3 * size of an integer). This is what happens when you do (&a + 1)
, and this is why you get an unexpected result. There is no value defined at this memory address, so you get undefined behavior.
It compiles because you cast the pointer to an int pointer, and if you want my advice, you should never silence compiler warnings about pointers with casts.