C:字符串错误打印两次
我正在使用 C 字符串,如以下程序所示:
#include <stdio.h>
int main(void){
char *player1 = "Harry";
char player2[] = "Rosie";
char player3[6] = "Ronald";
printf("%s %s %sn", player1, player2, player3);
return 0;
}
打印以下内容:
Harry Rosie RonaldRosie
为什么“Rosie”会打印两次?
回答
Ronald有 6 个字母,因此char player3[6]空终止符没有空格' '。
在您的情况下,它会打印Ronald内存中出现的任何内容,直到' '遇到a 为止。那恰好是Rosie。在找到' '.
一种解决方案(除了您如何初始化Harry和Rosie)是将元素数量增加 1 以为尾随提供空间' ':
char player3[7] = "Ronald";
- "Therefore, it will print whatever comes after Ronald in memory until it finds a ." is one of many possibilities as it is _undeifned behavior_ to use `"%s"` with a non-_string_.