Search code examples
arrayscimplicit-conversionpointer-arithmetic

What happens when I add something to Array name and try to access its memory location?


int i, paneerRoll[5]={89,45,35,2,3};
    printf("Element \t Address \t\t Value\n");
    for(i=0; i<5; i++)
    {
        printf("paneerRoll[%d] \t %p \t %d\n",i,&paneerRoll[i],paneerRoll[i]);
    }

    printf("\n\n\npaneerRoll \t %p \t %d\n",&paneerRoll,*paneerRoll);
    printf("(paneerRoll+2) \t %p \t %d",&paneerRoll+2,*(paneerRoll+2));

for this part

printf("(paneerRoll+2) \t %p \t %d",&paneerRoll+2,*(paneerRoll+2));

my output is

** (paneerRoll+2) 000000000061FE08 35 **

which is not equal to memory location of any element of array. so what is this addressing to?


Solution

  • From the C Standard (6.3.2.1 Lvalues, arrays, and function designators)

    3 Except when it is the operand of the sizeof operator or the unary & operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue. If the array object has register storage class, the behavior is undefined.

    So in this expression

    *(paneerRoll+2)
    

    the array designator paneerRoll is converted to pointer to the first element of the array. The expression paneerRoll + 2 points to the third element of the array. Dereferencing the expression *(paneerRoll+2) you get lvalue of the third element of the array.

    As for this expression

    &paneerRoll+2
    

    then the sub-expression &paneerRoll has the type int ( * )[5] and has the value of the address of the memory extent (the same address as the address of the first element of the array) occupied by the array.

    Using the expression

    &paneerRoll+2
    

    you get the address that is calculated like ( char * )paneerRoll + 2 * sizeof( int[5] ) that is far away from the allocated array