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

标签 c arrays string initialization c99

假设如下初始化:

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 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.

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

第 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 these rules.

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

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

相关文章:

javascript - jQuery - 从字符串数组中删除重复项

使用 malloc 连接字符串

javascript - 从包含的 JSONArray 中选择所有 JSONObjects

java - 如何解析xml中的字符串。安卓

c - strncpy() 段错误(再次)

c - SSL_library_init 在 gdb 下运行时导致 SIGILL

python - 使用 Python 删除子字符串

python - 如何将连接的列名称拆分为单独的列?

c - 需要处理大量定时器/超时的建议

c - C中最快的文件读取