加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何初始化联盟?

发布时间:2020-12-16 05:32:35 所属栏目:百科 来源:网络整理
导读:参见英文答案 Can a union be initialized in the declaration?3 如果它是一个结构,那么它可以完成 *p = {var1,var2..}; 但似乎这并不适用于联盟: union Ptrlist{ Ptrlist *next; State *s;};Ptrlist *l;l = allocate_space();*l = {NULL}; 只得到: expect
参见英文答案 > Can a union be initialized in the declaration?3
如果它是一个结构,那么它可以完成
*p = {var1,var2..};

但似乎这并不适用于联盟:

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

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

只得到:

expected expression before ‘{’ token

解决方法

在C99中,您可以使用d esignated union initializer:
union {
      char birthday[9];
      int age;
      float weight;
      } people = { .age = 14 };

在C,unions can have constructors.

在C89中,你必须明确地做.

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

thing_t foo;
foo.x = 2;

顺便说一句,你是否知道在C联合会,all the members share the same memory space?

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

输出:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读