Search code examples
cunions

Alignment of variable in union


Possible Duplicate:
A question about union in C

Assuming the following code:

#include <stdio.h>

int main()
{
    union a
    {
        int i;
        char ch[2];
    };
    union a u;
    u.ch[0]=3;
    u.ch[1]=2;
    printf("%d, %d, %d\n", u.ch[0], u.ch[1], u.i);
    return 0;
}

I want to know why ch[0] and ch[1] are on low order address of union. In stack if I have a Little Endian Byte they should be on higher order addresses. Can anybody explain memory representation of a union?


Solution

  • Since all members are placed at the start of the memory block occupied by the union, the union ought to be aligned such that all members of it are aligned as well.