How to initialize a union? [duplicate]

2019-03-24 08:11发布

This question already has an answer here:

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

标签: c unions
5条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-03-24 08:51

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

查看更多
小情绪 Triste *
3楼-- · 2019-03-24 08:53

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

查看更多
爷的心禁止访问
4楼-- · 2019-03-24 09:01

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

查看更多
Fickle 薄情
5楼-- · 2019-03-24 09:04
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;
 };
查看更多
beautiful°
6楼-- · 2019-03-24 09:06

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

查看更多
登录 后发表回答