starting address of array a and &a

前端 未结 5 1275
我在风中等你
我在风中等你 2021-02-03 14:03

In the below two lines,

char a[5]={1,2,3,4,5};
char *ptr=(char *)(&a+1);
printf(\"%d\",*(ptr-1));

This prints 5 on screen.Whereas when use

5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-03 14:25

    What you are running into is a subtlety of pointer arithmetic.

    The compiler treats "a" as a pointer to char - an entity that is 1 byte in size. Adding 1 to this yields a pointer that is incremented by the size of the entity (i.e. 1).

    The compiler treats "&a" as a pointer to an array of chars - an entity that is 5 bytes in size. Adding 1 to this yields a pointer that is incremented by the size of the entity (i.e. 5).

    This is how pointer arithmetic works. Adding one to a pointer increments it by the size of the type that it is a pointer to.

    The funny thing, of course, is that when it comes to evaluating the value of "a" or "&a", when dereferencing, they both evaluate to the same address. Which is why you see the values that you do.

提交回复
热议问题