1

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?

Community
  • 1
  • 1
Utkarsh Srivastav
  • 3,105
  • 7
  • 34
  • 53
  • 1
    This behavior of this code is undefined. See http://stackoverflow.com/questions/2310483/purpose-of-unions-in-c-and-c –  Dec 24 '11 at 15:44
  • You cannot read values from *both* members of a `union`. Paul's comment is trying to tell you that doing so produces undefined behavior. Asking questions about "why" you see certain undefined behaviors is nonsensical. – Cody Gray - on strike Dec 24 '11 at 16:06
  • @CodyGray, what makes you think that? Reading from another member than you have written to is only UB if the bit pattern is a trap representation for the type of that member. Since `char` usually don't have trap representations this is most certainly not an issue here. (To even avoid that completely one would have to use `unsigned char`.) – Jens Gustedt Dec 24 '11 at 16:18

2 Answers2

3

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.

jørgensen
  • 10,149
  • 2
  • 20
  • 27
0

This is just how a union works. It has nothing to do with endianess.
Each union member starts at the address where the union starts, and takes as much as it needs. So ch[0] will take the first address.

Endianess is only relevant when an integer type takes two or more bytes. Then, the most significant byte can be either the first or the last. But here you have two characters, the first is first, the second is second.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
ugoren
  • 16,023
  • 3
  • 35
  • 65