如何初始化联合对象? [英] How to initialize a union object?

查看:144
本文介绍了如何初始化联合对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果这是一个结构则是可以做到的。

  * P = {VAR1,VAR2 ..};

但似乎这并不工会工作

 工会Ptrlist
{
        Ptrlist *接下来的;
            状态;
};Ptrlist * L;
L = allocate_space();
* L = {NULL};

只得到:

 之前的预期前pression'{'令牌


解决方案

在C99中,可以使用A D <一个href=\"http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=/com.ibm.xlcpp8l.doc/language/ref/strin.htm\">esignated联合的初始化:

 工会{
      CHAR [9]的生日;
      INT年龄;
      浮重;
      } =人{。年龄= 14};

在C ++中,<一个href=\"http://stackoverflow.com/questions/321351/initializing-a-union-with-a-non-trivial-constructor\">unions可以构造。

在C89,你必须明确地做到这一点。

 的typedef工会{
  INT X;
  浮ÿ;
  无效* Z;
} thing_t;thing_t富;
foo.x = 2;

顺便说一句,你是否知道,在C工会,所有成员共享相同的内存空间

  INT的main()
{
   thing_t富;
   的printf(X:%P Y:%P Z:%P \\ N,
     &安培; foo.x,&安培; foo.y,&安培; foo.z);
   返回0;
}

输出的:


  

X:0xbfbefebc Y:0xbfbefebc Z:0xbfbefebc


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

解决方案

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

这篇关于如何初始化联合对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆