Akhil
Akhil

Reputation: 105

pointer to an array derefferencing

following is a section of code that I have written:

#include <stdio.h>
void main()
{
    int (*p)[2];
    int a[2] = {0, 1};
    p = &a;
    printf("p = %x\n",p);
    printf("&p = %x\n",&p);
    printf("a = %x\n",a);
    printf("&a = %x\n",&a);
    printf("*p = %x\n",*p);
    printf("*a = %x\n",*a);
}

Following is the output which I got:

p = bfd387c8
&p = bfd387c4
a = bfd387c8
&a = bfd387c8
*p = bfd387c8
*a = 0

Now I have this doubt that how could p and *p be equal. Actually p = a;*a = 0; then why *p is not equal to 0 also. Please this is my first question at stack overflow.Please help me out.

Upvotes: 2

Views: 102

Answers (2)

John Bode
John Bode

Reputation: 123578

Except when it is the operand of the sizeof or unary & operators, or is a string literal being used to initialize another array in a declaration, an expression of type "N-element array of T" will be converted ("decay") to an expression of type "pointer to T", and the value of the expression will be the address of the first element of the array.

When you declare an array, it's laid out in memory like so:

          +---+
  arr[0]: |   |
          +---+
  arr[1]: |   |
          +---+
           ...
          +---+
arr[N-1]: |   |
          +---+

Notice that there's no separate arr variable to store the address of the first element of the array; the address of the first element is the same as the address of the whole array.

Thus, the values of the expressions arr and &arr are the same, but the types are different (T * vs. T (*)[N]).

Since p evaluates to &a and *p evaluates to a, and since &a and a yield the same value, then p and *p will also yield the same value.

(*p)[0] == a[0] == *a == 0

Upvotes: 1

mch
mch

Reputation: 9814

your program should look like this:

#include <stdio.h>
int main()
{
    int (*p)[2];
    int a[2] = {0, 1};
    p = &a;
    printf("p = %p\n",(void*)p);
    printf("&p = %p\n",(void*)&p);
    printf("a = %p\n",(void*)a);
    printf("&a = %p\n",(void*)&a);
    printf("*p = %p\n",(void*)*p);
    printf("*a = %x\n",*a);
    printf("**p = %x\n",**p);
    return 0;
}

You should use %p and cast to (void*) to print pointer.

p points to the array a (which implies a == &a) and so p == *p. To get the first value of the array you have to use **p because it is an pointer to the array.

Upvotes: 3

Related Questions