【发布时间】:2017-02-02 14:33:06
【问题描述】:
我一直在尝试使用默认值初始化嵌套结构,并仅分配子结构字段的特定字段。这样我就不必初始化嵌套结构的所有内容。
从下面的示例代码中可以看出,它在尝试打印子子结构的字段值时会产生分段错误。有没有人建议一种更好的方法来初始化默认值而无需遍历每个字段? 谢谢
struct special_char
{
char c;
int size;
};
struct alphabet
{
struct special_char* special_c;
int special_char_size;
};
struct numeral
{
int array_numeral;
int size;
};
struct alpha_numeral
{
struct alphabet alpha;
struct numeral num;
int size;
};
int main()
{
printf(" Initialization of nested structures !\n");
struct alpha_numeral test = { { { 0 } } };
printf("values %d", test.alpha.special_c->size);
return 0;
}
输出:嵌套结构的初始化!
分段错误(核心转储)
【问题讨论】:
-
C 还是 C++?选择一个,答案会有所不同。
-
你在哪里为
special_char* special_c分配内存? -
它甚至不能编译为 C++。
标签: c data-structures struct initialization