看下面的代码:
#include<stdio.h>
int main(void)
{
char name[7]={'E','R','I','C'};
printf("%s",name);
}
它输出整个name
ERIC。为什么会这样?难道%s
不应该只有在我们初始化字符时才起作用吗?数组 name
如下:
char name[7]={'E','R','I','C','\0'}; //With NULL terminator
我不考虑以下内容,因为这显然假定了一个以 null 结尾的字符数组:
char name[7]="ERIC"
最佳答案
(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 arithmetic type, it is initialized to (positive or unsigned) zero;
因此,当你像这样初始化一个数组时:
char name[7]={'E','R','I','C'};
它等同于:
char name[7]={'E','R','I','C', 0, 0, 0};
所以 name
仍然以 null 结尾。
关于c - 为什么 "%s"格式说明符甚至可以用于没有 `\0` 的字符数组并一次打印其所有元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16382551/