【发布时间】:2020-04-26 19:27:25
【问题描述】:
当我通过以下方式声明字符串时,没有收到任何编译器警告:
static uint8_t test[3] = {'0','0','0'}; // (1)
static uint8_t test[3] = ""; // (2)
uint8_t test[3] = ""; // (3)
(2)和(3)有什么区别。这是可以做还是不好的编程习惯?
还有字符串是如何存储在内存中的?
我们有没有可能写超出 3 的大小?
当我这样做时:
uint8_t test[3] = ""; //
test[0] = 0 test[1] = 0 test[2] = 0 test[3] = /0 (null character indicating the end of the string)
或者做
uint8_t test[3] = "123";
test[0] = ‘1’
test[1] = ‘2’
test[2] = ‘3’
test[3] = /0 (null character indicating the end of the string)
空终止符存储在哪里?
和有什么区别
test[3] = ""
test[3] = '\0'
对我来说,这似乎是我将所有位置归零,但也将位置 3 作为起始地址归零,这就是我感到困惑的原因。
和
uint8_t test[3] = ""
uint8_t test[3] = '\0'
【问题讨论】:
-
请注意 1. 和 2. 不一样。在 2. 你得到一个
'\0'的数组,而在 1. 你得到一个'0'的数组。所以 1. 不是一个正确的以 null 结尾的字符串。 -
数字 1 和 2 具有静态 storage duration 和可能内部 linkage。 3 号没有。
-
严格来说,这些根本不是字符串。使用
uint8_t表示这些是 numerical 值的数组,它们恰好是根据字符/字符串文字初始化的...... -
@Blaze 你确定 2. 生成 3 个连续的 \0 吗?
-
@linuxfansaysReinstateMonica 是的,参见here:“所有未显式初始化的数组元素都以与具有静态存储持续时间的对象相同的方式隐式初始化。” 和@ 987654324@:“具有静态和线程本地存储持续时间的对象初始化如下[...]整数类型的对象被初始化为无符号零”