Manish Bharti - 7 months ago 26

C Question

first of all sorry for my English .

Now come to question

here is a code about the array to pointer

problem is that i dont understand the output

according to what i have studied > *p -----means value at address p is containing

and *(*p) value at address at (value at address p congaing )

then why the output is different

code

`---------------------------------------------------------------------------`

#include<stdio.h>

void main()

{

static int a[ ] = { 0, 1, 2, 3, 4 } ;

int *p[ ] = { a, a + 1, a + 2, a + 3, a + 4 } ;

printf ( "\n%u %u %d", p, *p, * ( *p ) ) ;

}

and output is

`3545106368 6293840 0`

please help me to understand this output .Keep it simple and easy for me

thanks in advance...........

Answer

In memory your arrays looks something like this:

+------+------+------+------+------+ | a[0] | a[1] | a[2] | a[3] | a[4] | +------+------+------+------+------+ ^ ^ ^ ^ ^ | | | | | +------+------+------+------+------+ | p[0] | p[1] | p[2] | p[3] | p[4] | +------+------+------+------+------+

I.e. each element of `p`

is pointing to the corresponding element in `a`

.

Then you have to learn that when using an array, it decays to a pointer to its first element, i.e. the expression `p`

is the same as `&p[0]`

. So when you are printing out `p`

then you are printing out the address of the first element of the array `p`

.

When you dereference the pointer given by `p`

, then you are effectively doing `*&p[0]`

. The dereference and address-of operators cancel each other out, so when you print `*p`

you are printing `p[0]`

which is the value of the first element in the array `p`

.

That element, `p[0]`

, is in turn a pointer to `a[0]`

. So when you dereference that pointer (in `**p`

, which is the same as `*p[0]`

) then you get the value of `a[0]`

.

Also, for any array *or* pointer `p`

and index `i`

, the expression `p[i]`

is the same as `*(p + i)`

. From that follows that `p[0]`

is the same as `*(p + 0)`

which is the same as `*(p)`

which is the same as `*p`

.

From that follows the logic that `p`

and `&p[0]`

are the same.

And to really screw you around, due to the commutative property of addition, the expression `*(p + i)`

is the same as `*(i + p)`

which leads to the peculiar but valid expression `i[p]`

.

Last but not least, when printing a pointer with `printf`

, you should really be using the `"%p"`

format. It takes a `void*`

as argument, and you also need to cast the pointers for the program to be valid. So your `printf`

call should look like

```
printf ( "%p %p %d\n", (void *) p, (void *) *p, **p ) ;
```

See e.g. this `printf`

(and family) reference for more information.