我是编程的新手,并且编写了以下代码:

#include <stdio.h>

int main(void)
{
   char x[] = "",
        y[] = "",
        z[] = "";

   printf("Enter a string: ");
   scanf("%s", x);

   printf("Enter another string: ");
   scanf("%s", y);

   printf("Enter one more string: ");
   scanf("%s", z);

   printf("\n");
   printf("x is %s\n", x);
   printf("y is %s\n", y);
   printf("z is %s\n", z);

   getch();
   return 0;
}


当我输入x的“ I”,y的“ am”和z的“ happy”时,结果如下:

x is ppy
y is appy
z is happy


有人知道是什么问题吗?谢谢!

最佳答案

char x[] = "";


等效于:

char x[1] = {'\0'};


如您所见,x的null终止符只有一个元素,没有足够的空间来存储任何非空字符串。 yz相同。

要解决此问题,请定义具有足够空间的xyz,最好在示例中使用fgets代替scanf

10-04 21:53
查看更多