c++ - 通过 "\0"而不是 memset() 批量初始化 char 数组

标签 c++ c arrays char

通常由 memset 初始化的字符数组。

我在我的项目代码中发现了由"\0"初始化的char数组。我还编译并检查了,它工作正常。

我的问题是这是批量初始化 char 数组的正确方法吗?

例如:

char a[20]="\0";
printf("%s", a);

最佳答案

是的,这是正确的方法之一。

对于

引用 C11,第 6.7.9 章

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.

并且,关于static存储变量的初始化,

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;

对于

引用 C++17,第 11.6.2 章

If there are fewer initializers than there are array elements, each element not explicitly initialized shall be zero-initialized.


所以,在你的情况下,

char a[20]="\0";

尝试将a[0]初始化为'\0'a[1]初始化为'\0' (对于空终止符),其余为 0。 FWIW,'\0' 的十进制值为 0,因此在这种情况下,数组中的所有元素都将具有值 0.

一些类似的初始化语句是

char a[20] = "";
char a[20] = {0};
char a[20] = {'\0'};

对于C++,建议in the other answer ,包括所有以前的语法,

char a[20] = {};

也可以。

关于c++ - 通过 "\0"而不是 memset() 批量初始化 char 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56428916/

相关文章:

c++ - 反转指向成员的指针(即获取包含结构的地址)

c++ - 如何获取直接连接到我的PC的计算机的IP地址

c - 警告 : '__builtin_snprintf' output may be truncated before the last format character [-Wformat-truncation=]

C:在文件之间传递变量

c++ - 我可以在 C++11 中使用具有值语义的多态容器吗?

c++ - 通过引用将值传递给 void 函数

在 for 循环中创建字符数组

C++ 不允许带有负索引的 vector ?

java - 将文档写入内部存储

php - 使用 javascript 和 php 自动通知?