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.
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 ) );
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With