U
Udo Steinberg
Hi,
The program below stores the 5 unsigned ints a, b, c, x and y in an
anonymous union, so that they share storage space with state[].
Additionally x and y share storage space with nums[]. The main
function displays the address of each of the 5 integers twice, first
using the member pointer table "members" and then using an instance of
myclass. The results are surprising: the values for x and y are
incorrect when using the member pointers.
laptop:~/scratch> g++ -W -Wall foo.cc -o foo
laptop:~/scratch> ./foo
a -> 0x8049718 0x8049718
b -> 0x804971c 0x804971c
x -> 0x8049718 0x8049720
y -> 0x804971c 0x8049724
c -> 0x8049728 0x8049728
This is g++ version 3.4.0 from the GNU compiler collection.
Any ideas?
-Udo.
#include <stdio.h>
class myclass
{
public:
union
{
unsigned state[];
struct
{
unsigned a;
unsigned b;
union
{
unsigned nums[];
struct
{
unsigned x, y;
};
};
unsigned c;
};
};
};
unsigned myclass::*members[] =
{
&myclass::a,
&myclass::b,
&myclass::x,
&myclass::y,
&myclass::c,
};
myclass foo;
int
main (void)
{
printf ("a -> %p %p\n", &(foo.*members[0]), &foo.a);
printf ("b -> %p %p\n", &(foo.*members[1]), &foo.b);
printf ("x -> %p %p\n", &(foo.*members[2]), &foo.x);
printf ("y -> %p %p\n", &(foo.*members[3]), &foo.y);
printf ("c -> %p %p\n", &(foo.*members[4]), &foo.c);
return 0;
}
The program below stores the 5 unsigned ints a, b, c, x and y in an
anonymous union, so that they share storage space with state[].
Additionally x and y share storage space with nums[]. The main
function displays the address of each of the 5 integers twice, first
using the member pointer table "members" and then using an instance of
myclass. The results are surprising: the values for x and y are
incorrect when using the member pointers.
laptop:~/scratch> g++ -W -Wall foo.cc -o foo
laptop:~/scratch> ./foo
a -> 0x8049718 0x8049718
b -> 0x804971c 0x804971c
x -> 0x8049718 0x8049720
y -> 0x804971c 0x8049724
c -> 0x8049728 0x8049728
This is g++ version 3.4.0 from the GNU compiler collection.
Any ideas?
-Udo.
#include <stdio.h>
class myclass
{
public:
union
{
unsigned state[];
struct
{
unsigned a;
unsigned b;
union
{
unsigned nums[];
struct
{
unsigned x, y;
};
};
unsigned c;
};
};
};
unsigned myclass::*members[] =
{
&myclass::a,
&myclass::b,
&myclass::x,
&myclass::y,
&myclass::c,
};
myclass foo;
int
main (void)
{
printf ("a -> %p %p\n", &(foo.*members[0]), &foo.a);
printf ("b -> %p %p\n", &(foo.*members[1]), &foo.b);
printf ("x -> %p %p\n", &(foo.*members[2]), &foo.x);
printf ("y -> %p %p\n", &(foo.*members[3]), &foo.y);
printf ("c -> %p %p\n", &(foo.*members[4]), &foo.c);
return 0;
}