akjlab
akjlab

Reputation: 170

Explanation required for address of union members

I have written the following code:

#include <iostream>
using namespace std;

union Packed
{
   char     i;
   short    j;
   int      k;
   long     l;
   float    f;
   double   d;
};

int main()
{
  cout<<"sizeof(Packed) = "<< sizeof(Packed)<<endl;
  Packed x;
  cout<<"Address j ="<<&(x.j)<<endl;
  cout<<"Address i ="<<&(x.i)<<endl;
  cout<<"Address k ="<<&(x.k)<<endl;
  cout<<"Address l ="<<&(x.l)<<endl;
  cout<<"Address f ="<<&(x.f)<<endl;
  cout<<"Address d ="<<&(x.d)<<endl;
  return 0;
}

Output:

sizeof(Packed) = 8

Address j =0x7fff587a71a0
Address i =

Address k =0x7fff587a71a0
Address l =0x7fff587a71a0
Address f =0x7fff587a71a0
Address d =0x7fff587a71a0

When I altered the code as follows:

  cout<<"Address j ="<<(long)&(x.j)<<endl;
  cout<<"Address i ="<<(long)&(x.i)<<endl;
  cout<<"Address k ="<<(long)&(x.k)<<endl;
  cout<<"Address l ="<<(long)&(x.l)<<endl;
  cout<<"Address f ="<<(long)&(x.f)<<endl;
  cout<<"Address d ="<<(long)&(x.d)<<endl;

I get the output:

Address j =140736718889408
Address i =140736718889408
Address k =140736718889408
Address l =140736718889408
Address f =140736718889408
Address d =140736718889408

I am little bit confused that why I am not getting a proper address in case of character variable in a union when I am just printing base address for all variables in a union which is supposed to be same as confirmed when "long" typecasted in the second part of the code.

Please provide an explanation for the confusion.The outputs are listed as obtained on a Fedora FC17 Linux machine.

Upvotes: 0

Views: 371

Answers (2)

4pie0
4pie0

Reputation: 29744

The reason for that is that C++ ostreams overload operator << for char * and takes them as a pointer to the C-style (NULL terminated) string and print it. Because Packed x is the union type object put on stack it has automatic storage duration and is not initialized to 0 (it would be the case if x had static or thread storage duration). So the value of x.i is undefined and this is why you have experienced the print-nothing behavior

Packed x;
cout<<"Address i ="<<&(x.i)<<endl; // nothing gets printed

This is undefined behavior.

You should cast the expression to a void const* pointer to print the address itself

Packed x;
cout<<"Address i ="<< static_cast< void const*> ( &x.i) << endl;

Upvotes: 0

Ulrich Eckhardt
Ulrich Eckhardt

Reputation: 17434

There's an overload for char const* variable in ostreams. Cast all pointer to void const* to get proper results.

Oh, and before I forget: Use static_cast() and don't ever use C-style casts unless you really know that you have to!

Upvotes: 5

Related Questions