关于C中的字符串输入

时间:2014-10-08 05:33:45

标签: c string

我是编程的初学者,我编写了以下代码:

#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;
}

当我进入&#34;我&#34;对于x,&#34; am&#34;对于y和&#34;快乐&#34;对于z,结果是这样的:

x is ppy
y is appy
z is happy

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

3 个答案:

答案 0 :(得分:7)

char x[] = "";

相当于:

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

如您所见,x只有一个元素用于空终止符,没有足够的空间来存储任何非空字符串。 yz也是如此。

要修复此问题,请定义xyz,并留出足够的空间,最好在示例中使用fgets代替scanf

答案 1 :(得分:0)

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

Replace these lines with :
printf("x is %s address of x: %u\n", x,x);
printf("y is %s address of y: %u\n", y,y);
printf("z is %s address of z: %u\n", z,z);

By doing so you will find:
Enter a string: i 
Enter another string: am
Enter one more string: happy

x is ppy    address of x: 1572060267
y is apply  address of y: 1572060266
z is happy  address of z: 1572060265

65 66 67 68 69 70
      i  \0
      a  m \0
h  a  p  p  y  \0

Third time when you enter 'happy' the memory location gets updated as above, since 'x' address is 67 so it starts printing from 67 unto NULL character i.e. \0.
In the same way 'y' and 'z'.

答案 2 :(得分:0)

这必须给出分段错误。

原因:

由于x,y,z是具有零个字符的数组(但请记住,&#39; \ 0&#39;将存在,因此有效的1个字节空间可用于x [],y []和z []) ,当你输入&#34; i&#34;时,2个字符将被有效地复制到x指向的地址位置,即&#39; i&#39;和&#39; \ 0&#39;。这本身将在打印时导致seg故障。同样适用于y []和z []。

现在,将seg故障放在一边并回答你的问题:

char x[] = "";
char y[] = "";
char z[] = "";

通常,执行时这些变量的地址位置如下。 设x []将覆盖内存位置763(记住,x [],y [],z []只有1个字节)。 堆栈增长的方式是y []将覆盖位置762,z []将覆盖位置761。

现在,正如阿妮塔·阿格拉瓦尔所说,这就是当你向计划提供意见时会发生的事情

760 761 762 763 764 765 766 767
            i   \0                
        a   m   \0                
    h   a   p   p   y   \0        

&#34;快乐&#34;覆盖&#34; am&#34;已经覆盖了#34;我&#34;。

因此,

1. printing x will start printing characters from location 763 till '\0' => ppy
2. printing y will start printing characters from location 762 till '\0' => appy
3. printing z will start printing characters from location 761 till '\0' => happy