gpt4 book ai didi

C 嵌套结构的默认初始化

转载 作者:太空宇宙 更新时间:2023-11-04 06:57:44 25 4
gpt4 key购买 nike

我一直在尝试使用默认值初始化嵌套结构,并仅分配子子结构字段的特定字段。这样我就不必初始化嵌套结构的所有内容。

正如您从下面的示例代码中看到的,它在尝试打印子子结构的字段值时生成段错误。有没有人建议一种更好的方法来初始化默认值而无需遍历每个字段?谢谢

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;
}

Output: Initialization of nested structures !
Segmentation fault (core dumped)

最佳答案

Does anyone suggest a better way of initializing default value without going through each field?

您已经演示过的结构初始化是一种将初始字段设置为特定值并让其余字段隐式初始化(​​为零)的简单方法。指定初始化器可用于指定要显式初始化的非初始成员。

As you can see from the sample code below, it generates a segmentation fault while trying to print the field values of sub-sub-structure.

迂腐地说,您并不是在访问子子结构。您正在访问由 test 的子结构指向的结构的字段。除了,不存在指向的结构,并且您(明确地)将指针初始化为 0,因此取消引用它具有未定义的行为。将其设置为指向一个对象:

struct special_char c = { 0 };
struct alpha_numeral test = { { &c } } ;

附言。初始值设定项的大括号过多。指针没有子对象。

关于C 嵌套结构的默认初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42004908/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com