How to initialize a union? [duplicate]

拟墨画扇 提交于 2019-12-03 10:18:20
Crashworks

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

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

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

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

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;
 };
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!