gpt4 book ai didi

c - 当字符串的长度大于它的字符长度时会发生什么?

转载 作者:行者123 更新时间:2023-12-02 01:31:29 28 4
gpt4 key购买 nike

char matrix_string[1000] = "the";

在上面的代码中,结果字符串“the”后面是一堆零或垃圾值吗?如果我知道这个字符串会随着我向它 append 值而变大,我该怎么办?

最佳答案

任何时候你初始化一个数组的项目少于数组可以容纳的数量时,数组的剩余部分被初始化为零。使用字符串文字作为初始值设定项也不异常(exception)。当您使用字符串文字来初始化数组时,该字符串之后的所有数组元素都将被初始化为零。

以下引用来自 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.

这就是 §6.7.9 第 10 段所说的关于具有静态存储持续时间的对象的初始化

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 matrix_string[1000] = "the";

','h','e','\0'放入数组的前四个元素并将其他 996 个元素设置为 0

关于c - 当字符串的长度大于它的字符长度时会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34033620/

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