Reputation:
I have a union with the declaration:
union test_u
{
int i;
char *str;
};
I am trying trying to initialize a variable with data in the "second" field, using the code:
union test_u test = {"Sample"}; // char *, not int
On attempting to compile this, I receive the error:
file.c:72:11: warning: initialization makes integer from pointer without a cast
Is it possible to initialize the variable in the same manner I have above? Shouldn't the compiler (under C89) accept either an int
to char *
in the initialization?
Upvotes: 2
Views: 241
Reputation: 121427
With C89, only the first member of the union is initialised. So you can just change the order of variables in union:
union test_u
{
char *str;
int i;
};
Upvotes: 2
Reputation: 18667
In C99, this is possible using designated initialisers:
union test_u test = { .str = "Sample" };
Upvotes: 5