C struct自动初始化值,数组初始化 [英] C struct automatic initialization values, array initializations

查看:149
本文介绍了C struct自动初始化值,数组初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我要有两个结构

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变量:

And I created a Chapter variable:

Chapter x1;

将其两个成员的值初始化为什么?是垃圾吗?还是零?在我的代码中,我得到了int0,但是我的助教告诉我这将是垃圾吗?

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

是否将用30个包含0/NULL值元素的结构填充?还是用垃圾值元素初始化?

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

推荐答案

这要视情况而定.除非明确初始化,否则

It depends. Unless initialized explicitly,

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

在具有自动存储期限的情况下,内容将不确定(是的,不确定" 垃圾" 更合适)./p>

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

引用C11,第§6.7.9/p10

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;

这篇关于C struct自动初始化值,数组初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆