be*****@hotmail.com wrote:
I have a structure that contains a union that Id like to initialize at
compile time... something like:
//global declare and initialize
fullStructType var1 = { unionMember.union1.field1 = 100;
unionMember.union1.field2 = 200 };
fullStructType var2[2] = { { unionMember.union2 = 300 } ,
{ unionMember.union2 = 400 } };
where the structures are defined as :
typedef struct
{
union
{
fieldStructType union1;
alt_u16 union2;
} unionMember;
} fullStructType;
and
typedef struct{
alt_u8 field1;
alt_u8 field2;
} fieldStructType;
I get a bunch of errors on the variable declarations.. whats the
proper syntax??
You really should post your actual code. You have the first needed
typedef last, the second needed typedef before that, but after it is
used. And those alt_* types aren't any too useful. This sort of thing
makes it difficult to help. In any case, compare your effort to the
following:
#include <stdio.h>
typedef struct
{
unsigned char field1;
unsigned char field2;
} fieldStructType;
typedef struct
{
union
{
fieldStructType union1;
unsigned short union2;
} unionMember;
} fullStructType;
//global declare and initialize
fullStructType var1 = {.unionMember.union1 = {100, 200} };
fullStructType var2[2] = {[0].unionMember.union2 = 300,
[1].unionMember.union2 = 400
};
int main(void)
{
printf("var1.unionMember.union1.field1=%u\n",
var1.unionMember.union1.field1);
printf("var1.unionMember.union1.field2=%u\n",
var1.unionMember.union1.field2);
printf("var2[0].unionMember.union2=%u\n",
var2[0].unionMember.union2);
printf("var2[1].unionMember.union2=%u\n",
var2[1].unionMember.union2);
return 0;
}
[output]
var1.unionMember.union1.field1=100
var1.unionMember.union1.field2=200
var2[0].unionMember.union2=300
var2[1].unionMember.union2=400