#include <stdio.h>
int main(){
char p[5] = "ABCD";
int* ip = (int *)p;
printf("%d \n", *(ip + 0)); // 1145258561
printf("%d \n", ip); // 6422016
}
Could anybody please explain to me the output of this program?
#include <stdio.h>
int main(){
char p[5] = "ABCD";
int* ip = (int *)p;
printf("%d \n", *(ip + 0)); // 1145258561
printf("%d \n", ip); // 6422016
}
Could anybody please explain to me the output of this program?
Here you cast the char[4]
, p
, into an int*
and initialize ip
with the result:
int* ip = (int *)p;
Here you dereference ip
, which, since it's an int*
means that it will read sizeof(int)
bytes to form an int
from the address ip
points at:
printf("%d \n", *(ip + 0)); // 1145258561
Since int
s are often 4 bytes, it will often seem to work, but it violates the strict aliasing rule and results in undefined behavior. Also, if an int
is 8 bytes, the program would have undefined behavior since it would then read outside the char[4]
.
Here you print the value of ip
as an int
, but it is a pointer, so again, the program will have undefined behavior. Also, a pointer is often 8 bytes so it will likely cause undefined behavior for that reason too.
printf("%d \n", ip); // 6422016
To properly print pointers, use %p
and cast the pointer to void*
:
printf("%p\n", (void*) ip);