C语言 如何初始化联合?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7008784/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to initialize a union?
提问by lexer
If it's a structthen it can be done
如果是,struct那么它可以完成
*p = {var1, var2..};
But seems this doesn't work with union:
但似乎这不适用于union:
union Ptrlist
{
Ptrlist *next;
State *s;
};
Ptrlist *l;
l = allocate_space();
*l = {NULL};
Only to get:
只为获得:
expected expression before ‘{' token
回答by Crashworks
In C99, you can use a designated union initializer:
在 C99 中,您可以使用指定联合初始化程序:
union {
char birthday[9];
int age;
float weight;
} people = { .age = 14 };
In C++, unions can have constructors.
在 C++ 中,联合可以有构造函数。
In C89, you have to do it explicitly.
在 C89 中,您必须明确地执行此操作。
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?
顺便说一句,您是否知道在 C 联合中,所有成员共享相同的内存空间?
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
x:0xbfbefebc y:0xbfbefebc z:0xbfbefebc
回答by Kamath
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
回答by duedl0r
Assign one of the fields to NULL. Since it is a union all the fields will be NULL.
将字段之一分配给 NULL。由于它是一个联合,因此所有字段都将为 NULL。
回答by shengy
I don't have a Stateclass so I replaced it with an int.
我没有State课程,所以我用 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
所以这样,n的值被初始化为10
回答by Jeegar Patel
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;
};

