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

标签 c arrays struct initialization

如果我有两个结构

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/

相关文章:

c++ int 数组 - 删除一个 int 并移动数组的其余部分

c - 结构体成员不会存储在变量中

c - 在运行时如何从内存访问C结构成员?

有人能告诉我段错误的原因吗 - 这个程序中的(核心转储)错误

c - c中逐个字符的结构成员

c++ - 未命名结构的编译器重新排序

c - 如何在 sizeof 运算符的帮助下初始化数组?

arrays - 拆分字符串数组

c - 如何在C中访问结构数组内的结构成员

c - sprintf 缓冲区大小