char label[8] = "abcdefgh";
char arr[7] = "abcdefg";
printf("%s\n",label);
printf("%s",arr);
Run Code Online (Sandbox Code Playgroud)
====输出==========
ABCDEFGH
abcdefgÅ
为什么Å附加在字符串arr的末尾?我在Turbo C++中运行C代码.
Hei*_*nzi 14
printf期望以NUL结尾的字符串.将char数组的大小增加1,为终止NUL字符腾出空间(由= "..."初始化程序自动添加).
如果你没有NUL终止你的字符串,printf将继续阅读,直到它找到一个NUL字符,这样你将获得或多或少的随机结果.
您的变数label和arr不字符串.它们是字符数组.
要成为字符串(并且为了能够将它们传递给在<string.h>中声明的函数),它们需要在为它们保留的空间中使用NUL终结符.
标准中"字符串"的定义
7.1.1 Definitions of terms
1 A string is a contiguous sequence of characters terminated by and including
the first null character. The term multibyte string is sometimes used
instead to emphasize special processing given to multibyte characters
contained in the string or to avoid confusion with a wide string. A pointer
to a string is a pointer to its initial (lowest addressed) character. The
length of a string is the number of bytes preceding the null character and
the value of a string is the sequence of the values of the contained
characters, in order.