im trying to learn pointers and im confused in second line, can someone explain how it works?
if we suppose 'a' base address is 100
int a[3][3] = {6, 2, 5, 0, 1, 3, 4, 9, 8};
printf("%p \n", a+1); // output is gonna be 112
printf("%p \n", *(a+1));// still output is gonna be 112
How does the pointer arithmetic and the dereference operator (*) work in the second line of code? Why does the printf statement printf("%p \n", *(a+1)); output the memory address 112 instead of the integer value at that address? Thanks in advance
Remember that for any array or pointer a
and index i
, the expression a[i]
is exactly the same as *(a + i)
.
If we apply it to your example, then a + 1
is a pointer to the second element of the array a
. It's the same as &a[1]
.
And *(a + 1)
is a[1]
, which is an array and therefore will decay to a pointer to its first element, meaning that a[1]
is the same as &a[1][0]
.
While these two pointers, &a[1]
and &a[1][0]
, have different types, they both point to the same location. Which is very easy to see once we draw it out, with the pointers added:
+---------+---------+---------+---------+--------------------+ | a[0][0] | a[0][1] | a[0][2] | a[1][0] | ... (not relevant) | +---------+---------+---------+---------+--------------------+ ^ |- &a[1] |- &a[1][0]
To expand on the different types, &a[1]
is a pointer to an array of three int
elements, or int (*)[3]
.
The other pointer, &a[1][0]
, is a pointer to a single int
element, and therefore have the type int *
.