cdummy
cdummy

Reputation: 455

How this code works - regarding union initialization in c?

I got the output 0 2 for this program..... but don't know why?
Please explain i think only int i is initialized with 512.
But how ch[1] got the value 2.

#include <stdio.h>
int main()
{
    union a /* declared */
    {
        int i;   char ch[2];
    };
    union a z = { 512 };   

    printf("%d%d", z.ch[0], z.ch[1]);
    return 0;
}

Upvotes: 1

Views: 331

Answers (5)

George Skoptsov
George Skoptsov

Reputation: 3951

Union declaration means that all its members are allocated the same memory. So your int i and char ch[2] are referencing the same memory space -- in other words, they are aliased. Whenever you change one, you will change the other as well.

Now, assuming your ints are 32-bit wide and you're on a little-endian system like x86, i = 512 (512 == 0x00000200) actually looks like this in memory:

0x00  0x02  0x00  0x00.

with the first two values corresponding directly to the 2-character array:

ch[0] ch[1]

So you get ch[0] == 0x0 and ch[1] == 0x02.

Try setting your i = 0x1234 and see what effect it will have on your character array.

Based on your question, it's possible that you may want to use a struct instead of union -- then its members would be allocated in memory sequentially (one after the other).

Upvotes: 4

Peter Miehle
Peter Miehle

Reputation: 6070

you intermix 'struct' with 'union'. in union you collect different typed and named data into one field (with lenght = maximum (size of data)), which you can access, and for which you have yourself make sure you get the right data.

your example allocs memory for max(int, char[2]) It is no difference, if you say z.i = 32 or z.ch[0]=' '

Upvotes: 1

ipc
ipc

Reputation: 8143

You got 0 2 for good reasons but the C standard says that the behavior is not defined. If you write i then the value of ch can be theoretically anything.

However, the gcc assures that the data will be well-aligned.

Upvotes: 0

user529758
user529758

Reputation:

Simple: 512 = binary 1000000000, so ch[0] will get the 8 zeroes (assuming your system is little endian) and ch[1] will get the 10 part, which, in decimal, is 2.

Upvotes: 1

thumbmunkeys
thumbmunkeys

Reputation: 20764

512 is 0x200 in hex, so the first byte of your union is 0 the second is 2. If you dont specify which union member should be initialized, the first one will be taken, the int in your case.

You get 2 for the second byte of your string as the first byte of ch is intialized with 0, the second one with 2.

Upvotes: 3

Related Questions