C struct automatic initialization values, array in

2020-04-28 01:45发布

问题:

If I were to have two structs

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;

And I created a Chapter variable:

Chapter x1;

What would the values of its two members be initialized to? Is it garbage? Or is it zero? In my code I got 0 for the int, but my TA told me it would be garbage?

Also, if I were to declare an array of chapters:

Chapter chapters[30];

Would it be filled with 30 structs with 0/NULL valued elements? Or initialized with garbage valued elements?

回答1:

It depends. Unless initialized explicitly,

  • If the variable has static (or thread) storage duration, the members will be initialized to 0 or equivalent.

  • In case it has automatic storage duration, the contents will be left indeterminate (yes, "indeterminate" is more appropriate than "garbage").

Quoting C11, chapter §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;