本文介绍了嵌套结构变量初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在C中初始化此嵌套结构?
How can I initialize this nested struct in C?
typedef struct _s0 {
int size;
double * elems;
}StructInner ;
typedef struct _s1 {
StructInner a, b, c, d, e;
long f;
char[16] s;
}StructOuter; StructOuter myvar = {/* what ? */ };
推荐答案
要将所有内容初始化为0(正确的类型)
To initialize everything to 0 (of the right kind)
StructOuter myvar = {0};
要将成员初始化为特定值
To initialize the members to a specific value
StructOuter myvar = {{0, NULL}, {0, NULL}, {0, NULL},
{0, NULL}, {0, NULL}, 42.0, "foo"};
/* that's {a, b, c, d, e, f, s} */
/* where each of a, b, c, d, e is {size, elems} */
编辑
如果您使用的是C99编译器,则还可以使用指定的初始化程序",如下所示:
If you have a C99 compiler, you can also use "designated initializers", as in:
StructOuter myvar = {.c = {1000, NULL}, .f = 42.0, .s = "foo"};
/* c, f, and s initialized to specific values */
/* a, b, d, and e will be initialized to 0 (of the right kind) */
这篇关于嵌套结构变量初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!