user142162
user142162

Reputation:

Unable to initialize second item in a union

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

Answers (2)

P.P
P.P

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

Jack Kelly
Jack Kelly

Reputation: 18667

In C99, this is possible using designated initialisers:

union test_u test = { .str = "Sample" };

Upvotes: 5

Related Questions