Program:
#include
int main(void) {
int x[4];
printf(\"%p\\n\", x);
printf(\"%p\\n\", x + 1);
printf(\"%p\\n\", &x);
p
Even though x
and &x
evaluate to the same pointer value, they are different types. Type of x
after it decays to a pointer is int*
whereas type of &x
is int (*)[4]
.
sizeof(x)
is sizeof(int)*4
.
Hence the numerical difference between &x
and &x + 1
is sizeof(int)*4
.
It can be better visualized using a 2D array. Let's say you have:
int array[2][4];
The memory layout for array
is:
array
|
+---+---+---+---+---+---+---+---+
| | | | | | | | |
+---+---+---+---+---+---+---+---+
array[0] array[1]
| |
+---+---+---+---+---+---+---+---+
| | | | | | | | |
+---+---+---+---+---+---+---+---+
If you use a pointer to such an array,
int (*ptr)[4] = array;
and look at the memory through the pointer, it looks like:
ptr ptr+1
| |
+---+---+---+---+---+---+---+---+
| | | | | | | | |
+---+---+---+---+---+---+---+---+
As you can see, the difference between ptr
and ptr+1
is sizeof(int)*4
. That analogy applies to the difference between &x
and &x + 1
in your code.