I just saw this code snippet Q4 here and was wondering if I understood this correctly.
#include <stdio.h>
int main(void)
{
int a[5] = { 1, 2, 3, 4, 5 };
int *ptr = (int*)(&a + 1);
printf("%d %d\n", *(a + 1), *(ptr - 1));
return 0;
}
Here's my explanation:
int a[5] = { 1, 2, 3, 4, 5 };
=> a
points to the first element of the array. In other words: a
contains the address of the first element of the array.
int *ptr = (int*)(&a + 1);
=> Here &a
will be a double pointer and point to the whole array. I visualize it like this: int b[1][5] = {1, 2, 3, 4, 5};
, here b
points to a row of a 2D array. &a + 1
should point to the next array of integers in the memory (non-existent) [kind of like, b + 1
points to the second (non-existent) row of a 2D array with 1 row]. We cast it as int *
, so this should probably point to the first element of the next array (non-existent) in memory.
*(a + 1)
=> This one's easy. It just points to the second element of the array.
*(ptr - 1)
=> This one's tricky, and my explanation is probably flawed for this one. As ptr
is an int *
, this should point to int previous to that pointed by ptr
. ptr
points to the non-existent second array in memory. So, ptr - 1 should probably point to the last element of the first array (a[4]
).