2009-11-02 42 views
1
char label[8] = "abcdefgh"; 
char arr[7] = "abcdefg"; 

printf("%s\n",label); 
printf("%s",arr); 

====输出==========字符数组问题

ABCDEFGH

abcdefgÅ

为什么在所附字符串arr的结尾? 我在Turbo C++中运行C代码。

回答

14

printf预计NUL终止的字符串。将char数组的大小增加1,以便为终止NUL字符留出空间(由= "..."初始化程序自动添加)。

如果你不能NUL终止你的字符串,printf将继续阅读,直到它找到一个NUL字符,所以你会得到一个或多或少的随机结果。

+0

这里的“串”的

定义是在这背后的理论教程:http://www.cplusplus.com/doc/tutorial/ntcs/ – Heinzi 2009-11-02 06:44:25

+7

或者,您也可以使用空括号,例如'char label []',允许编译器为你正确设置数组大小。 – user200783 2009-11-02 06:48:15

+1

或者删除显式大小并让编译器进行计数;电脑擅长计数! – 2009-11-02 06:48:56

4

您的字符串不是空终止的,所以printf正在运行到垃圾数据中。您需要在字符串末尾使用'\ 0'。

2

使用GCC(在Linux上),它打印更多的垃圾:

abcdefgh°ÃÕÄÕ¿UTÞÄÕ¿UTÞ· 
abcdefgabcdefgh°ÃÕÄÕ¿UTÞÄÕ¿UTÞ· 

这是因为,要打印两种字符数组作为字符串(使用%S)。

这工作得很好:

char label[9] = "abcdefgh\0"; char arr[8] = "abcdefg\0"; 

printf("%s\n",label); printf("%s",arr); 

不过,你不用提 “\ 0” 作了明确规定。只要确保数组的大小足够大,即比字符串中的字符数多1。

+2

不需要明确写出“\ 0”:双引号字符串隐式地以NUL结尾。你只需要确保数组足够大。 – Heinzi 2009-11-02 06:48:41

+0

是的。更新了我的答案。谢谢 – 2009-11-02 07:05:31

6

您的变量labelarr不是字符串。他们是字符数组。

要成为字符串(并且为了能够将它们传递给<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. 
+0

+1正式答案! – Heinzi 2009-11-02 08:29:37