#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?
CodePudding user response:
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 work. 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 if ip
as an int
, but it is a pointer, which often has the size 8. It will therefore likely cause undefined behavior.
printf("%d \n", ip); // 6422016
To properly print pointers, use %p
and cast the pointer to void*
:
printf("%p\n", (void*) ip);
CodePudding user response:
The string (char array) p is casted as int pointer ip.
Each c-char has a length of 8 bit, each c-int a length of 32 bit. This is why you could cast your 4 chars to one int.
If you print *(ip 0) you print the value of the pointer at it's first address (The char values converted to int).
Printing ip gives you the pointer name itself.
If you'd print &ip you'd get the address of the first element of the pointer.