char label[8] = "abcdefgh";
char arr[7] = "abcdefg";
printf("%s\n",label);
printf("%s",arr);====output==========
abcdefgh防御
abcdefg
为什么在字符串arr的末尾追加?我正在运行C代码的涡轮C ++。
发布于 2009-11-02 06:43:14
printf期望以NUL结尾的字符串。将char数组的大小增加一个,以便为终止NUL字符(它由= "..."初始化程序自动添加)腾出空间。
如果不终止字符串,printf将继续读取,直到找到NUL字符为止,因此您将得到或多或少的随机结果。
发布于 2009-11-02 06:44:15
您的字符串不是空终止的,因此printf正在运行在垃圾数据中。您需要在字符串末尾使用'\0‘。
发布于 2009-11-02 06:46:59
使用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。
https://stackoverflow.com/questions/1659750
复制相似问题