Thread overview
struct with union problem
Aug 25, 2003
Ant
Re: struct with union problem - converted to C
Aug 25, 2003
Ant
Aug 26, 2003
Walter
Dec 07, 2003
Robert
August 25, 2003
is this right?

struct Value
{
int type1;
int type2;
union data
{
char c;
void* pointer;
};
}

void main()
{
printf("D test\n");

Value v;
v.type1 = 1;
v.type2 = 2;
v.data.c = 'a';

printf("v:\n");
printf("\ttype1 = %d\n",v.type1);
printf("\ttype2 = %d\n",v.type2);
printf("\tc = %c\n",v.data.c);
printf("\tpointer = %p\n",v.data.pointer);
}

output:
D test
v:
type1 = 97
type2 = 2
c = a
pointer = 0x61

expected ouput:
D test
v:
type1 = 1
type2 = 2
c = a
pointer = 0x61

something is wrong here,
can't I do that?

Ant


August 25, 2003
In article <bic7s9$2g2b$1@digitaldaemon.com>, Ant says...
>
>is this right?
>output:
>D test
>v:
>type1 = 97
>type2 = 2
>c = a
>pointer = 0x61

after converting the program to C the ouput looks better:
C test
v:
type1 = 1
type2 = 2
c = a
pointer = 0xbffff861

C program:
typedef struct
{
int type1;
int type2;
union
{
char c;
void* pointer;
} data;
} Value;

void main()
{
printf("C test\n");

Value v;
v.type1 = 1;
v.type2 = 2;
v.data.c = 'a';

printf("v:\n");
printf("\ttype1 = %d\n",v.type1);
printf("\ttype2 = %d\n",v.type2);
printf("\tc = %c\n",v.data.c);
printf("\tpointer = %p\n",v.data.pointer);
}

DMD 0.70

Ant


August 26, 2003
You've found a bug. I'll take care of it. -Walter


December 07, 2003
I found the same problem also in case of union with struct.

<<code>>
import std.c.stdio;

union A {
char c;
struct { short s; }
struct { long  l; }
int a;
struct { float f; }
}

void main() {
A a;
printf("%d\n", (byte*)&a.c - (byte*)&a);
printf("%d\n", (byte*)&a.s - (byte*)&a);
printf("%d\n", (byte*)&a.l - (byte*)&a);
printf("%d\n", (byte*)&a.a - (byte*)&a);
printf("%d\n", (byte*)&a.f - (byte*)&a);
}

<<output>>
0
2
8
0
16

Robert (Japanese)