Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is that for a pointer *p, p[0] is the address stored at p and p[1] is the address of p itself?

The code

int n = 25;  
int *p = &n;  
printf("%x\n %d\n %x\n", p, p[0], p[1]);

returns:

\<adress-of-p  
25  
\<adress-of-p>  

Of course I would never do this but in K&R states that

"if pa is a pointer, expressions may use it with a subscript; pa[i] is identical to *(pa+i).

so I was curious.

like image 808
daniel Avatar asked Oct 17 '25 13:10

daniel


2 Answers

This statement

printf("%x\n %d\n %x\n", p, p[0], p[1]);

invokes undefined behavior by two reasons.

The first one is that to output a pointer you should use a correct conversion specifier. The second one is that you may not dereference a pointer like this p[1] that does not point to a valid object.

Instead you could write for example

printf("%p\n %d\n %p\n", ( void * )p, p[0], ( void * )( p + 1 ) );
like image 60
Vlad from Moscow Avatar answered Oct 20 '25 01:10

Vlad from Moscow


When you evaluate p[1] in your code, you are invoking undefined behavior so your program can do anything.

It is undefined behavior because p points at n which is just a single integer, not an array of integers. So p[0] is n, but p[1] is undefined. Basically this is an array overflow bug.

like image 21
David Grayson Avatar answered Oct 20 '25 01:10

David Grayson