gpt4 book ai didi

C struct自动初始化值,数组初始化

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

如果我有两个结构

typedef struct {
int number_of_lines;
char lines[MAX_CHAPTER_LINES][MAX_STR_SIZE + 1];
} Chapter;

typedef struct {
char name[MAX_STR_SIZE + 1];
int number_of_chapters;
Chapter chapters[MAX_CHAPTERS];
} Book;

然后我创建了一个 Chapter 变量:

Chapter x1;

它的两个成员的值会被初始化成什么?是垃圾吗?或者它是零?在我的代码中,我为 int 得到了 0,但我的助教告诉我这将是垃圾?

此外,如果我要声明一个章节数组:

Chapter chapters[30];

它会填充 30 个具有 0/NULL 值元素的结构吗?或者用垃圾值元素初始化?

最佳答案

这取决于。除非明确初始化,

  • 如果变量具有静态(或线程)存储持续时间,则成员将被初始化为 0 或等效值。

  • 如果它有自动存储期限,内容将是不确定的(是的,“不确定”“垃圾”更合适)。

引用 C11,章节 §6.7.9/p10

If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static or thread storage duration is not initialized explicitly, then:

— if it has pointer type, it is initialized to a null pointer;

— if it has arithmetic type, it is initialized to (positive or unsigned) zero;

— if it is an aggregate, every member is initialized (recursively) according to these rules, and any padding is initialized to zero bits;

— if it is a union, the first named member is initialized (recursively) according to these rules, and any padding is initialized to zero bits;

关于C struct自动初始化值,数组初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42547849/

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