C struct automatic initialization values, array initializations

后端 未结 1 1328
萌比男神i
萌比男神i 2021-01-24 15:54

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         


        
1条回答
  •  走了就别回头了
    2021-01-24 16:50

    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;

    0 讨论(0)
提交回复
热议问题