Endianness problem in C when pass by reference 32/64 bit
I am struggling with an endianness problem in below example. In this main() passes address of 32 bit integer and myfunc() receives it in 64 bit.
#include <stdint.h>
#include <s开发者_如何学运维tdio.h>
void myfunc(uint64_t *b)
{
printf("%llx\n", *b);
if ((*b & 255) == 127)
printf("\n It works\n");
else
printf("\n Not working\n");
}
main()
{
uint32_t a = 127;
printf("\n%lx\n", a);
myfunc(&a);
}
It works correctly on little endian platform(Windows).
7f
28ff780000007f
It works
But it fails on big endian(AIX).
7f
7fdeadbeef
Not working
I think when we pass the address of 32 bit and receives in 64bit, on big endian platform it receives in the other 32 bits. But I am not sure. Please help me to understand what is happening behind this. i cant correctly write the first line of program here.
Many Thanks Ann
First of all, you code triggers undefined behavior. You allocate a 32-bit variable a
and then (in myfunc()
) try to use it as if it was 64-bit - of larger size, so you effectively try to access outside a legally allocated variable. This can cause whatever consequences and your program just can't work right because what you're trying to do makes no sense from the C Standard point of view.
精彩评论