S
Sid
Hi folks,
I wrote this code to test if I get the same address for all the
variables in a union but for some reason the address I got when I used
a char variable in a union seems bizarre- can anyone help explain why
I get a bizzarre address for a char variable inside a union ? In other
words why is &(x.i) not 0012FED0 in the code below ?
Below is the source code
#include <iostream>
using namespace std;
union Packed { // Declaration similar to a class
char i;
short j;
int k;
long l;
float f;
double d;
// The union will be the size of a
// double, since that's the largest element
}; // Semicolon ends a union, like a struct
int main() {
cout << "sizeof(Packed) = "
<< sizeof(Packed) << endl;
Packed x;
cout <<" &x=" << &x << endl ;
x.i = 'c';
cout << x.i << endl;
cout << "&(x.i)=" << &(x.i) << endl;
x.j=32;
cout <<x.j<< endl;
cout << "&(x.j)="<< &(x.j) << endl;
x.k =58;
cout <<x.k << endl;
cout <<"&(x.k)="<<&(x.k) << endl;
x.l=1000000;
cout << x.l << endl;
cout <<"&(x.l)=" << &(x.l) << endl;
x.d = 3.14159;
cout << x.d << endl;
cout <<"&(x.d)=" << &(x.d) << endl;
x.f=3.14f;
cout << x.f << endl;
cout <<"&(x.f)=" << &(x.f) << endl;
} ///:~
OUTPUT OF THE ABOVE CODE BELOW
sizeof(Packed) = 8
&x=0012FED0
c
&(x.i)=c╠╠╠╠╠╠╠╠╠╠╠└
↕ ???????????????????????????????????????
32
&(x.j)=0012FED0
58
&(x.k)=0012FED0
1000000
&(x.l)=0012FED0
3.14159
&(x.d)=0012FED0
3.14
&(x.f)=0012FED0
I wrote this code to test if I get the same address for all the
variables in a union but for some reason the address I got when I used
a char variable in a union seems bizarre- can anyone help explain why
I get a bizzarre address for a char variable inside a union ? In other
words why is &(x.i) not 0012FED0 in the code below ?
Below is the source code
#include <iostream>
using namespace std;
union Packed { // Declaration similar to a class
char i;
short j;
int k;
long l;
float f;
double d;
// The union will be the size of a
// double, since that's the largest element
}; // Semicolon ends a union, like a struct
int main() {
cout << "sizeof(Packed) = "
<< sizeof(Packed) << endl;
Packed x;
cout <<" &x=" << &x << endl ;
x.i = 'c';
cout << x.i << endl;
cout << "&(x.i)=" << &(x.i) << endl;
x.j=32;
cout <<x.j<< endl;
cout << "&(x.j)="<< &(x.j) << endl;
x.k =58;
cout <<x.k << endl;
cout <<"&(x.k)="<<&(x.k) << endl;
x.l=1000000;
cout << x.l << endl;
cout <<"&(x.l)=" << &(x.l) << endl;
x.d = 3.14159;
cout << x.d << endl;
cout <<"&(x.d)=" << &(x.d) << endl;
x.f=3.14f;
cout << x.f << endl;
cout <<"&(x.f)=" << &(x.f) << endl;
} ///:~
OUTPUT OF THE ABOVE CODE BELOW
sizeof(Packed) = 8
&x=0012FED0
c
&(x.i)=c╠╠╠╠╠╠╠╠╠╠╠└
↕ ???????????????????????????????????????
32
&(x.j)=0012FED0
58
&(x.k)=0012FED0
1000000
&(x.l)=0012FED0
3.14159
&(x.d)=0012FED0
3.14
&(x.f)=0012FED0