Union

All the addresses of the union variables should be the same:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int main()
{
    union x
    {
        int s;
        double f;
        char t;
        long r;
        bool e;
    };
    x uni;
    cout << &uni.f << endl << &uni.s << endl << &uni.t << endl
    << &uni.r << endl << &uni.e;
    return 0;
}


Why is char's address different?
thanks
Last edited on
Try this instead:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
using namespace std;

int main()
{
    union x
    {
        int s;
        double f;
        char t;
        long r;
        bool e;
    };
    x uni;
    cout << &uni.f << endl << &uni.s << endl << (int*)&uni.t << endl
    << &uni.r << endl << &uni.e;
    return 0;
}


When you pass a char pointer to cout (which is what the address of a char is in this context), you don't get that pointer output like you do for all the others; it is overloaded to treat it as a pointer to an array of char (i.e. a C-style string) and outputs that C-style string.

In my code above, I have changed the char pointer to an int pointer so that you do get the value of the pointer, and you can now see that it is indeed the same address.

It has the same address, but &char will result in cout using the << overload for char pointers (c strings). It will print out the value of the char due to this, rather than the address. Try giving the char a certain value then output its address. To output the address, cast it to a void* when you pass it to cout.

EDIT: ninjad
Last edited on
Topic archived. No new replies allowed.