gpt4 book ai didi

c - 初始化为空字符串的字符数组元素的值

转载 作者:太空狗 更新时间:2023-10-29 16:58:31 24 4
gpt4 key购买 nike

假设如下初始化:

char mystr[4] = "";

C99标准是否保证初始化为空字符串的字符数组会将字符数组中的所有元素初始化为空字节?例如,标准是否保证 mystr[2] == '\0'

这些初始化怎么样:

char myfoo[4] = { '\0' };
char mybar[4] = { 0 };

虽然我很确定显式设置字符数组的第一个元素将保证将其余元素隐式初始化为 0,但我怀疑字符串文字初始化会导致复制到数组——因此意味着 单个 \0 被复制到数组,而其余元素未初始化。

最佳答案

第 6.7.8 节,第 21 段:

If there are fewer initializers in a brace-enclosed list than there are elements or membersof an aggregate, or fewer characters in a string literal used to initialize an array of knownsize than there are elements in the array, the remainder of the aggregate shall beinitialized implicitly the same as objects that have static storage duration.

静态存储时长的对象是如何初始化的?

第 6.7.8 节,第 10 段:

If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static 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;
  • if it is a union, the first named member is initialized (recursively) according to theserules.

char是算术类型,所以初始化为0,呵呵,你高枕无忧

关于c - 初始化为空字符串的字符数组元素的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16972527/

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