#include <stdio.h>
#include <stdlib.h>
int main (int argc, char *argv[]) {
char hello[5];
hello [0] = 'H';
hello [1] = 'e';
hello [2] = 'l';
hello [3] = 'l';
hello [4] = 'o';
char world[5];
world [0] = 'W';
world [1] = 'o';
world [2] = 'r';
world [3] = 'l';
world [4] = 'd';
printf ("%s %s!\n", hello, world);
return EXIT_SUCCESS;
}
当我运行上述代码时,我会得到:
Hello WorldHello!
有人能解释一下为什么我的输出要么是重复的单词,要么打印出奇怪的数字和字母吗? 这是因为我没有包含 '\0' 吗?
printf()
传递两个非字符串并告诉它给出了两个字符串来调用未定义的行为。任何事情都可能发生。你很幸运发生的事情基本上是良性的。如果您颠倒定义“hello”和“world”的顺序,您可能会关心自己看到的内容。 - Jonathan Leffler