Various arithmetic pointer values ​​when receiving an array address

Program:

#include<stdio.h> int main(void) { int x[4]; printf("%p\n", x); printf("%p\n", x + 1); printf("%p\n", &x); printf("%p\n", &x + 1); } 

Output:

 $ ./a.out 0xbff93510 0xbff93514 0xbff93510 0xbff93520 $ 

I expect the next version of the program to be released. For example:

 x // 0x100 x+1 // 0x104 Because x is an integer array &x // 0x100 Address of array &x+1 // 0x104 

But the result of the last statement is different than expected. &x also the address of the array. Thus, increasing 1 on this will print the address increased by 4. But &x+1 indicates the address increasing by 10. Why?

+49
c pointers language-lawyer
Nov 18 '15 at 9:05
source share
5 answers
 x -> Points to the first element of the array. &x ->Points to the entire array. 

Pounced on a descriptive explanation here: http://arjunsreedharan.org/post/69303442896/the-difference-between-arr-and-arr-how-to-find

SO link: Why is arr and & arr the same?

+62
Nov 18 '15 at 9:14
source share

In case 4, you get 0x100 + sizeof x and sizeof x is 4 * sizeof int = 4 * 4 = 16 = 0x10.

(On your system, sizeof int is 4).

+26
Nov 18 '15 at 9:10
source share

Easy thumbrule to evaluate:

Any increment pointer points to the next memory location of its base type. .

The base type & x is int (* p) [4] , which is a pointer to an array of 4 integers .

So, the next pointer of this type will point to 16 bytes (assuming int will be 4 bytes) from the original array.

+9
Nov 18 '15 at 12:57
source share

Even if x and &x evaluate the same pointer value, they are different types. Type x after it decays to a pointer is int* , while type &x is int (*)[4] .

sizeof(x) sizeof(int)*4 .

Therefore, the numerical difference between &x and &x + 1 is sizeof(int)*4 .

It can be better visualized using a 2D array. Say you have:

 int array[2][4]; 

Memory layout for array :

 array | +---+---+---+---+---+---+---+---+ | | | | | | | | | +---+---+---+---+---+---+---+---+ array[0] array[1] | | +---+---+---+---+---+---+---+---+ | | | | | | | | | +---+---+---+---+---+---+---+---+ 

If you use a pointer to such an array,

 int (*ptr)[4] = array; 

and look at the memory through a pointer, it looks like this:

 ptr ptr+1 | | +---+---+---+---+---+---+---+---+ | | | | | | | | | +---+---+---+---+---+---+---+---+ 

As you can see, the difference between ptr and ptr+1 is equal to sizeof(int)*4 . This analogy applies to the difference between &x and &x + 1 in your code.

+3
Nov 25 '15 at 5:45
source share

Believe it or not, the behavior of your program is undefined !

&x + 1 actually only points to an array, as @ i486's answer skillfully points. You do not own this memory. Even trying to assign a pointer to it is undefined behavior, not to mention trying to dereference it.

-6
Nov 18 '15 at 9:28
source share



All Articles