2014-10-08 24 views
-1

字符串輸入我在編程初學者,我寫了下面的代碼:關於用C

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

當我輸入「I」爲X「是」爲y和「快樂」爲Z,結果是這樣的:

x is ppy 
y is appy 
z is happy 

有沒有人知道是什麼問題?謝謝!

回答

7
char x[] = ""; 

等同於:

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

正如你看到的,x先後爲空終止只有一個元素,沒有足夠的空間來存儲任何非空字符串。對於yz也是如此。

爲了解決這個問題,定義xyz有足夠的空間,而且最好在你的榜樣使用fgets,而不是scanf

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'. 
0

這必須給出分段錯誤。

原因是:

因爲x,y,z是零個字符陣列(但要記住, '\ 0' 將存在,可用於X如此有效地1字節的空間[],Y []和當輸入「i」時,2個字符將被有效地複製到x指向的地址位置,即'i'和'\ 0'。這本身會在打印時導致分段錯誤。同樣的東西適用於y []和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   
會發生什麼

「開心」會覆蓋覆蓋「i」的「am」。

因此,

​​3210