2

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?

timrau
  • 22,578
  • 4
  • 51
  • 64

2 Answers2

5

In C99, this is possible using designated initialisers:

union test_u test = { .str = "Sample" };
Jack Kelly
  • 18,264
  • 2
  • 56
  • 81
  • The syntax `str: "Sample"` is also possible in C89. (Not sure if it's a GCC extension though). – user703016 Jun 06 '12 at 22:29
  • @Cicada: Your syntax is an old GCC extension (obsolete since GCC 2.5, but GCC supports the C99 syntax as an extension to C89): http://gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html – Jack Kelly Jun 07 '12 at 07:41
2

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;
};
P.P
  • 117,907
  • 20
  • 175
  • 238