c - 为什么 "%s"格式说明符甚至可以用于没有 `\0` 的字符数组并一次打印其所有元素?

标签 c string null-terminated null-character

看下面的代码:

#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"

最佳答案

根据 the c11 specification

(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/

相关文章:

c - 您将 sysv/posix 消息队列用于什么用途?

Python 2.7 类属性奇怪的行为

python - 在 Python 中使用 re.findall() 返回所有重叠模式?

julia - 从 julia 的字节向量中读取空终止字符串

c - 我应该如何在有效输入和缓冲区溢出的 shellcode 之间进行分隔?

C 程序链接到错误版本的函数

objective-c - 从Blender导出模型以在iOS App中使用

c - 如何让 getc() 返回笑脸以外的字符?

java - 无法检测到多个空间?

c - 当所有值都有效时如何终止可变长度数组?