gpt4 book ai didi

c - 将字符串初始化为 {0, } 有什么作用?

转载 作者:行者123 更新时间:2023-12-03 20:25:27 25 4
gpt4 key购买 nike

我见过这样的代码:

char str[1024] = {0, };

并怀疑它类似于这样做:
char str[1024];
str[0] = '\0';

但我在上面找不到任何东西,所以我不确定。

这是什么(称为),它有什么作用?

免责声明:我知道之前可能有人问过并回答过这个问题,但搜索 {0, }是惊人的难。如果你能指出重复,我很乐意删除这个问题。

最佳答案

不,它们不一样。
这个说法

char str[1024] = {0, };
将第一个元素初始化为给定值 0 ,并且所有其他元素都将被初始化,就好像它们具有静态存储一样,在这种情况下,值为 0 .从语法上讲,这类似于使用
char str[1024] = {0};
报价 C11 ,第 6.7.9 章,第 21 页

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.


并且,来自 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;


另一方面
char str[1024];
str[0] = '\0';
只初始化第一个元素,其余元素保持统一化,包含不确定的值。

关于c - 将字符串初始化为 {0, } 有什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62328762/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com