如何初始化联盟?

前端之家收集整理的这篇文章主要介绍了如何初始化联盟?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
参见英文答案 > Can a union be initialized in the declaration?3
如果它是一个结构,那么它可以完成 @H_403_3@*p = {var1,var2..};

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

@H_403_3@union Ptrlist { Ptrlist *next; State *s; }; Ptrlist *l; l = allocate_space(); *l = {NULL};

只得到:

@H_403_3@expected expression before ‘{’ token

解决方法

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

在C,unions can have constructors.

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

@H_403_3@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

@H_403_3@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&C++相关文章