2014-10-17 92 views
11

錯誤我有這樣的代碼:中止陷阱6用C

void drawInitialNim(int num1, int num2, int num3) 
{ 
    int board[2][50]; //make an array with 3 columns 
    int i; // i, j, k are loop counters 
    int j; 
    int k; 

    for(i=0;i<num1+1;i++)  //fill the array with rocks, or 'O' 
     board[0][i] = 'O';  //for example, if num1 is 5, fill the first row with 5 rocks 
    for (i=0; i<num2+1; i++) 
     board[1][i] = 'O'; 
    for (i=0; i<num3+1; i++) 
     board[2][i] = 'O'; 

    for (j=0; j<2;j++) {  //print the array 
     for (k=0; k<50;k++) { 
     printf("%d",board[j][k]); 
     } 
    } 
    return; 
} 

int main() 
{ 
    int numRock1,numRock2,numRock3; 
    numRock1 = 0; 
    numRock2 = 0; 
    numRock3 = 0; 
    printf("Welcome to Nim!\n"); 
    printf("Enter the number of rocks in each row: "); 
    scanf("%d %d %d", &numRock1, &numRock2, &numRock3); 
    drawInitialNim(numRock1, numRock2, numRock3); //call the function 

    return 0; 
} 

當我編譯這個用gcc,它是好的。當我運行該文件時,輸入值後我會得到中止陷阱6錯誤。

我看了其他文章關於這個錯誤,他們不幫我。

+2

'INT板[2] [50];' - > int board [3] [50];' – BLUEPIXY 2014-10-17 18:25:24

+0

但即使如此,50是一個可能溢出的幻數。 – 5gon12eder 2014-10-17 18:28:00

回答

2

嘗試這種情況:

void drawInitialNim(int num1, int num2, int num3){ 
    int board[3][50] = {0}; // This is a local variable. It is not possible to use it after returning from this function. 

    int i, j, k; 

    for(i=0; i<num1; i++) 
     board[0][i] = 'O'; 
    for(i=0; i<num2; i++) 
     board[1][i] = 'O'; 
    for(i=0; i<num3; i++) 
     board[2][i] = 'O'; 

    for (j=0; j<3;j++) { 
     for (k=0; k<50; k++) { 
      if(board[j][k] != 0) 
       printf("%c", board[j][k]); 
     } 
     printf("\n"); 
    } 
} 
+0

非常感謝你!有用! – user1753491 2014-10-17 19:29:49

18

你寫入內存你不擁有:

int board[2][50]; //make an array with 3 columns (wrong) 
        //(actually makes an array with only two 'columns') 
... 
for (i=0; i<num3+1; i++) 
    board[2][i] = 'O'; 
     ^

改變這一行:

int board[2][50]; //array with 2 columns (legal indices [0-1][0-49]) 
     ^

要:

int board[3][50]; //array with 3 columns (legal indices [0-2][0-49]) 
     ^

當創建一個數組,用來價值初始化[3]表示數組大小。
訪問現有數組時,索引值爲零基於

對於創建的數組:int board[3][50];
法律指數板[0] [0] ...板[2] [49]

EDIT爲了解決壞輸出評論和初始化評論

添加一個額外的 「\ n」 表示格式化輸出:

變化:

... 
    for (k=0; k<50;k++) { 
    printf("%d",board[j][k]); 
    } 
} 

     ... 

到:

... 
    for (k=0; k<50;k++) { 
    printf("%d",board[j][k]); 
    } 
    printf("\n");//at the end of every row, print a new line 
} 
... 

初始化板變量:

int board[3][50] = {{0}};//initialize all elements of 2d array to zero 
+0

是的,它確實修復了錯誤,ryyker。謝謝! – user1753491 2014-10-17 18:42:37

+0

@ user1753491 - 此外,板是一個整數數組,當做任務時,你不應該用零填充它們而不是'O'嗎? (board [2] [i] ='O';'應該是board [2] [i] = 0;') – ryyker 2014-10-17 18:51:12

+0

@ryyker我想讓它們成爲我的程序的一個O.我認爲我可以用ASCII碼做到這一點。你懂我的意思嗎?我不想處理char數組。 – user1753491 2014-10-17 19:02:14