unions

can someone explain the allocation of memory for unions on a little endain and big
endain processors
There's was a relationship between the endianness of the hardware an the allocation of unions?
Yeah there is, http://www.cplusplus.com/doc/tutorial/other_data_types/

Im not too sure, but here is a memory diagram from that article:

http://www.cplusplus.com/doc/tutorial/other_data_types/union.gif

I imagine that it would just be the mirror image of that.
Last edited on
You're right. My mistake.
The link give a nice explination about how to use unions but it does'nt explains much about allocation of memory in different endains. do u have some other link if possible
The thing that threw me was your use of the term allocation.

It's all about layout of the record.

Consider this example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <stdint.h>

union U
{
    uint32_t i32;

    struct S
    {
        unsigned char a, b, c, d;
    } s;
};

int main()
{
    U u;
    u.i32 = 0x01020304;

    std::cout
        << (unsigned)u.s.a << '.'
        << (unsigned)u.s.b << '.'
        << (unsigned)u.s.c << '.'
        << (unsigned)u.s.d << std::endl;

    return 0;
}


What is the output and why?
@kbw,
Sorry,I dont want to irritate u by saying that i dont have an idea of what 'uint32_t' is. I read it on http://www.cplusplus.com/reference/clibrary/cstdint
but still it did'nt get inside my crust..
I would be thankful to u if u can clear my concepts...I'm also trying
Last edited on
It is a 32 bit unsigned int.

EDIT: Did you read the links Owain posted above? You may need to read them again. And read about endianness. http://en.wikipedia.org/wiki/Endianness
Last edited on
I ran the program above for you.

32bit Intel: 4.3.2.1
64bit Intel: 4.3.2.1
32bit ppc: 1.2.3.4
64bit ppc: 1.2.3.4
@kbw Thans for providing me the above link.Than was some real stuff to deal with. A diagram(Mapping registers to memory locations) explains the effect of endainness for 8,16 and 32 bits,but what if I declare union of 24 bits ???
Topic archived. No new replies allowed.