starting address of array a and &a

前端 未结 5 1277
我在风中等你
我在风中等你 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:09

    The difference is in the type of the pointer that you get:

    • Array name a by itself represents a pointer to the initial element of the array. When interpreted in that way, e.g. in an expression a+1, the pointer is considered to point to a single character.
    • When you take &a, on the other hand, the pointer points to an array of five characters.

    When you add an integer to a pointer, the number of bytes the pointer is moved is determined by the type of the object pointer to by the pointer. In case the pointer points to char, adding N advances the pointer by N bytes. In case the pointer points to an array of five chars, adding N advances the pointer by 5*N bytes.

    That's precisely the difference that you are getting: your first example advances the pointer to the element one past the end of the array (which is legal), and then move it back to the last element. Your second example, on the other hand, advances the pointer to the second element, and then moves it back to point to the initial element of the array.

提交回复
热议问题