简体   繁体   English

使用缓冲区[100] = {0,}的初始化如何在C语言中工作?

[英]How does the initialization using buffer[100] = {0, } work in C language?

In the load data part of a program written in C language, I see the initialization of a buffer is done like this: 在用C语言编写的程序的加载数据部分中,我看到缓冲区的初始化是这样完成的:

char buffer[100] = {0, };

But I'm not sure about what values are assigned by this statement. 但是我不确定这个陈述赋予了什么值。 Please share some ideas. 请分享一些想法。

Does this depend on the compiler or is it a language feature? 这取决于编译器还是语言功能?

And what is the point using a comma after that zero, if this statement is equivalent to: 如果此语句等​​效于以下,那么在该零之后使用逗号的重点是什么:

char buffer[100] = {0};

Is it, by any chance, because the coder only want to make sure that the first element is zero, and don't care about the rest? 是不是因为编码器只想确保第一个元素为零,而不关心其余元素?

Does this depend on the compiler or is it a language feature? 这取决于编译器还是语言功能?

The behaviour is specified by the language standard. 行为由语言标准指定。 The current standard ( C11 §6.7.9 Initialization / 21 , which is at page 141) describes what happens when you supply fewer initializers than elements of an aggregate: 当前的标准( C11 §6.7.9初始化/ 21,这是在141页)介绍,当你不是总的要素供给较少的初始化发生了什么:

If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration. 如果括号括起的列表中的初始值设定项少于聚合的元素或成员,或者用于初始化已知大小的数组的字符串文字中的字符数少于数组中的元素,则聚合的其余部分应为隐式初始化与具有静态存储持续时间的对象相同。

So, the elements that are not specified are initialized to \\0 . 因此,未指定的元素将初始化为\\0

The value(s) given (a single 0 in this case) are used, and then all other members are filled with zeros. 给出的值(在这种情况下为单个0 ),然后所有其他成员都用零填充。

Had you said char buffer[100] = {1, }; 如果你说char buffer[100] = {1, }; , the array would contain a 1 and 99 zeros. ,数组将包含1和99个零。

buffer[100] = {literal, }将第一个元素初始化为文字值,其余部分初始化为0另一方面, buffer[100] = {0}将所有元素初始化为0代码等效于buffer[100] = {0}因为它们都将所有元素初始化为0.RichieHindle的buffer[100] = {1, }说明了整点。

Initializers for an array of a given size are assigned to array members on a one-to-one basis. 给定大小的数组的初始值设定项以一对一的方式分配给数组成员。 If there are too few initializers for all members, the remaining members are initialized to 0. Listing too many initializers for a given size array is an error. 如果所有成员的初始值设定项太少,则其余成员初始化为0.为给定大小的数组列出太多初始值设定项是错误的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM