Structs and Unions !!!

davideo

I look like Gizmo
Staff member
Administrator
Staff Moderator
Treasurer
Blogger
Joined
Jan 22, 2008
Posts
15,120
Country
UK
Region
Boston, Lincs
I've got the following bit of code that works as expected under Wx-Dev-C on my PC but doesn't give the same results under StormC4 on my Miggy :double

Code:
typedef union
{
    struct { unsigned char l,h; } B;
    unsigned int W;
} pair;
main(void)
{
    int i;
    pair PC;
    PC.B.h=PC.B.l=0;
    PC.W=0;
    PC.B.l = 0xFF;
    PC.B.h = 0xEE;
    printf("l - %02x \n",PC.B.l);
    printf("h - %02x \n",PC.B.h);
    printf("W - %08x \n",PC.W);
    PC.W = 0xDEAD;
    printf("l - %02x \n",PC.B.l);
    printf("h - %02x \n",PC.B.h);
    printf("W - %08x \n",PC.W);
    printf("char = %d\n",sizeof(unsigned char));
    printf("int  = %d\n",sizeof(unsigned int));
    i=getchar();
}

On the PC I get
Code:
l - ff
h - ee
W - 0000eeff
l - ad
h - de
W - 0000dead
char = 1
int = 4

On the Miggy the only differences are the first W is eeff0000 and the second l and h are both 0

Now if I'm reading structs and unions correctly they should have both given me the same answer.

Any clues were I'm going wrong?
 
Big-endian vs little-endian?
 
Yes that's what I was thinking - Bluddy C :double

And the number of bits is making a difference. Declaring "unsigned short int W" is making a difference too.
 
Yup, that's an endianness issue - the single biggest gotcha with otherwise-awesome pointer/union shenanigans in C...
 
'tis indeed a very agreeable word :D

yeah and int is 16bit on Amiga, but 32bit on PC - these days. Used to be 16bit though :(
 
Thanks guys.

Made a bit more progress with your help (y)
 
Back
Top Bottom