This code does "pointer punning". It is one of the way of using the binary representation of one type as another type.
In C it violates the strict alising rules and it is Undefined Behavior.
In your case (assuming 4 bytes int
) the content of the char
array is going to be interpreted as int
value.
int main(void)
{
char arr[] = {0,1,2,3};
int *ip = (int *)arr;
printf("%d - 0x%08x\n", *ip, *ip);
}
output
50462976 - 0x03020100
The hex value is easier to interpret as two digits of the number represent one byte in the memory. As you see the the number is "reversed" comparing to the representation in the memory. It is because PC computers are little endian and least significant byte is store first. https://en.wikipedia.org/wiki/Endianness
To avoid Undefined Behavior you should copy the array into the integer
int main(void)
{
char arr[] = {0,1,2,3};
int ip;
memcpy(&ip, arr, sizeof(ip));
printf("%d - 0x%08x\n", ip, ip);
}
How is it possible that the int pointer ip can point to an element of
arr if the array itself it's char?
In the end, any object (it does not matter what its type is) is just a bunch of chars (bytes) stored in the memory. Your pointer is referencing some location in memory.