How to initialize a union? [duplicate]

2019-03-24 08:57发布

问题:

This question already has an answer here:

  • Can a union be initialized in the declaration? 3 answers

If it's a struct then it can be done

*p = {var1, var2..};

But seems this doesn't work with union:

union Ptrlist
{
        Ptrlist *next;
            State *s;
};

Ptrlist *l;
l = allocate_space();
*l = {NULL};

Only to get:

expected expression before ‘{’ token

回答1:

In C99, you can use a designated union initializer:

union {
      char birthday[9];
      int age;
      float weight;
      } people = { .age = 14 };

In C++, unions can have constructors.

In C89, you have to do it explicitly.

typedef union {
  int x;
  float y;
  void *z;
} thing_t;

thing_t foo;
foo.x = 2;

By the way, are you aware that in C unions, all the members share the same memory space?

int main () 
{
   thing_t foo;
   printf("x: %p  y: %p  z: %p\n",
     &foo.x, &foo.y, &foo.z );
   return 0;
}

output:

x: 0xbfbefebc y: 0xbfbefebc z: 0xbfbefebc



回答2:

There is difference between initialization and assignment. Initialization is intelligent, while for the assignment you need to resolve proper address.


    Example
    char str[] = "xyz";    // works - initialization 
    char str[10];
    str = "xyz";            // error - assignment
                           // str is a address that can hold char not string

    Similarly
    Ptrlist l = {NULL};    // works - initialization 
    Ptrlist *l;
    l->next = NULL;        // works assignment
    l = {NULL};            // is assignment, don't know the address space error



回答3:

Assign one of the fields to NULL. Since it is a union all the fields will be NULL.



回答4:

I don't have a State class so I replaced it with an int.

this is my code:

union Ptrlist
{
    Ptrlist *next;
    int *n;
};


int main(int argc, char** argv)
{
    Ptrlist *l = new Ptrlist;

    // I'm using a way c++ allocated memory here, you can change it to malloc.
    l->n = new int;
    *(l->n) = 10;

    // Because you used an union, n's and next's addres is same 
    // and this will output 10
    printf("%d", *(l->next));

    getch();
    return 0;
}

So in this way, n's value is initialized to 10



回答5:

union Ptrlist1
{
    char *next;
    char  *s;
};

union Ptrlist1 l = {  NULL };

see this a example of union initialization. in your case i think there is some mistake in

  Ptrlist how can be member of union..??

you should write

 union Ptrlist
 {
    union Ptrlist *next;
        State *s;
 };


标签: c unions