[英]Is there a quick way to initialise a struct array with the same attributes?
struct child {
char name[32];
int height;
};
struct child group_a[8];
我想用相同的名称和高度初始化 group_a 中的每个孩子,例如 name = "XXX" 和 height = "100"。
有没有快速的做法,而不是struct child group_a[8] = {{"XXX", 100}, {"XXX", 100}, ..., {"XXX", 100}}
?
如果没有更深层次的预处理器魔法,它就无法在标准 C 中完成。 但是,指定初始化程序中的范围有扩展。 它受到主要编译器(GCC、CLANG、Intel)的支持。
struct child group_a[] = {
[0 ... 7] = { .name = "XXX", .height = 100 }
};
尝试使用这样的复合文字:
int i = 8;
while(i--)
group_a[i] = (struct child) { "XXX", 100 };
也许有点蹩脚,但为什么不使用宏呢?
#define H {"XXX", 100}
struct child group_a[8] = {H, H, H};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.