starting address of array a and &a

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

    Arrays aren't pointers! Read section 6 of the comp.lang.c FAQ for more information.

    Let's look at your second case first, since it's the more "normal" and idiomatic looking. Line by line:

    1. You declare an array a containing 5 char elements.
    2. The name of the array (a) decays into a pointer to its first element in this context. You add 1 to that and assign the result to ptr. ptr points to the 2. No cast is necessary, though you have one.
    3. You subtract 1 from ptr and then dereference and print - hence you get the 1.

    Now, let's address the first case, again line by line:

    1. You declare an array a containing 5 char elements.
    2. You take the address of a, yielding a char (*)[5] type pointer. You then add 1 to this pointer - because of pointer arithmetic this new pointer pasts to the byte just after 5 in memory. Then you typecast (required, this time) and assign this value to ptr.
    3. You subtract 1 from ptr and then dreference and print. ptr is a char *, so this subtraction simply moves the pointer back by one from "one past the end of a" to point to the last element of a. Hence you get the 5.

    Finally, the reason char *ptr=&a+1; gives a warning is because C requires conversions between pointer types to have an explicit cast. As mentioned above, &a is of type char (*)[5], not char *, so to assign that value to a char * variable, you'll need the explicit cast.

提交回复
热议问题