2015-09-11 20 views
-1

我編寫了一個程序,用C編寫一個2D數組,用於打印包含用戶輸入圖形表示的2D表格。我編譯並運行了這個程序,但無論按下Return還是Ctrl + D用於EOF,getchar並沒有像預期的那樣出現在循環中的指令上。我在這裏做錯了什麼?爲什麼不是getchar退出?

int main() 
{ 
    /*ignore these comments, they are outdated todo lists*/ 
    /* make vars init here, change for to while */ 
    /* finish printing */ 
    int c; 
    int i, sec, other; 
    char ndigit[3][8]; 

    while((c = getchar()) != EOF) { 
     if (c == '\n' || '\t' || ' ') { 
      for(i = 0; i < 63; ndigit[1][i] += 1); 
       ; 
     } 
     else if (c >= '0' || c <= '9') { 
      for(sec = 0; sec < 63; ndigit[2][sec] += 1) 
       ; 
     } 
     else 
      for(other = 0; other < 63; ndigit[3][other] += 1) 
       ; 
    } 
    for (i = 0; i <= 3; ++i) 
     for (sec = 0; sec <= 8; sec++) 
      printf("%s\n", ndigit[i][sec]); 
} 
+2

1)'c =='\ n'|| '\ t'|| '''總是如此。 2)不改變索引變量。 3)越界。 – BLUEPIXY

+1

爲什麼John Doe的名字?我邀請你用你的真實身份註冊Stack Overflow(以及一些加入你的方式)。 –

回答

1

編譯所有警告&調試信息(gcc -Wall -Wextra -g,特別是在Linux上,我建議初學者和專家)。您可能會從編譯器中獲得許多有用的警告(如果可能,請使用最近版本的GCC,因爲GCC隨着時間的推移正在改進其診斷....)。改進你的代碼,直到你根本沒有任何警告。然後使用調試器gdb),特別是一步一步地運行你的程序。也許添加一些調試打印。您可能也有興趣使用valgrindaddress sanitizer

注意在:

for(other = 0; other < 63; ndigit[3][other] += 1); 

other沒有發生變化(你可能忘了一個other++,然後如果添加它,你會得到一個buffer overflow,因爲ndigit[][Ĵ]品牌僅適用於0 < = i < 3和0 < = j < 8);所以你有一個無限循環。

A buffer overflowundefined behavior(UB)的一種方法。你應該非常害怕 UB和努力工作,以避免UB。 Here我解釋了爲什麼。

+0

你說得對,我確實忘記了增加變量,而且事實上,在向循環中添加增量後,我確實發生了段錯誤。然而,當我在for循環的條件中有其他<63時,我爲什麼會出現段錯誤而感到困惑。這怎麼可能? –