以下代码按预期工作并输出ABC
:
#include <stdio.h>
void printString (char toPrint [100]);
int main()
{
char hello [100];
hello[0] = 'A';
hello[1] = 'B';
hello[2] = 'C';
hello[3] = '\0';
printString(hello);
}
void printString (char toPrint [100])
{
int i = 0;
while (toPrint[i] != '\0')
{
printf("%c", toPrint[i]);
++i;
}
}
但是如果我删除添加空字符的行
hallo[3] = '\0';
我得到随机输出等wBCÇL, ╗BCÄL, ┬BCNL
。
为什么呢?我期望 printString() 中的循环永远运行,因为它没有遇到“\ 0”,但是“A”、“B”和“C”发生了什么?为什么 B 和 C 仍然出现在输出中,但 A 被一些随机字符替换?