如何初始化联盟?

参见英文答案 > 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: %p\n",&foo.x,&foo.y,&foo.z );
   return 0;
}

输出

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

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...