Search code examples
cpointerscastingimplicit-conversionpointer-arithmetic

How does this C code work? The ptr assignment is unclear


#include <stdio.h>

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

    return 0;
}

The output is: 2 7

I'm unable to find out how the outcome came to be.


Solution

  • Arrays used in expressions are implicitly converted to pointers to their firs elements.

    So in this expression *(a+1) the array designator a is converted to pointer of the type char * to its first element and the expression a + 1 points to the second element of the array. Dereferencing the pointer expression (a+1) like *(a+1) you get the second element of the array, Actually the expression *(a+1) is the same as the expression a[1].

    This expression &a has the pointer type char ( * )[7] that points to the whole array a of the type char[7].

    This expression (&a+1) points to the memory after the last element of the array and has the same type char ( * )[7]. This pointer expression is casted to the type char *.

    char *ptr =(char*)(&a+1);
    

    So the pointer p points to the memory after the last element of the array a.

    The expression ptr-1 points to the last element of the array and dereferencing this expression like *(ptr-1) you get the last element of the array.