关于C语言中的空字符
这是我的程序: 点击链接查看该程序 在此程序中,
char c[5] = "hello\0world";
当我使用以下行打印字符串 c
时:
printf("\nstring c=%s", c);
它给出以下输出(末尾带有微笑符号,与下面的符号不完全一样,但我可以说它是一个笑脸符号:
string c=hello(•‿•)
为什么不打印 hello 在输出中?因为字符串的大小只有5?
提前致谢。
This is my program:
Click link to see the program
In this program,
char c[5] = "hello\0world";
When I print the string c
using the following line:
printf("\nstring c=%s", c);
It gives the following output (with smile symbol at the end, not exactly like the symbol below, but I can say it is a smiley symbol:
string c=hello(•‿•)
Why doesn't it print hello
In the output? because the size of string is only 5?
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
数组
c
只有 5 个字符宽,对于该大小的数组来说,给定的初始值设定项包含太多字符。因此仅使用字符串常量的前 5 个字符来初始化数组。这意味着该数组仅包含字符
'h'
、'e'
、'l'
、'l' 和<代码>'o'。换句话说,您没有字符串,因为它不是以 null 结尾的。因此
printf
最终读取到了数组末尾,触发了未定义行为。如果省略数组大小:
它将足够大以适合整个初始值设定项。然后 printf 将打印“hello”,因为它将在空字节处停止读取。
The array
c
is only 5 characters wide, and the initializer given has too many characters for an array that size. So only the first 5 characters of the string constant are used to initialize the array.This means that the array contains only the characters
'h'
,'e'
,'l'
,'l'
, and'o'
. In other words, you don't have a string because it's not null terminated. Soprintf
ends up reading past the end of the array triggering undefined behavior.If you omit the array size:
It will be made large enough to fit the entire initializer. Then
printf
will print "hello" since it will stop reading at the null byte.