簡體   English   中英

中止 C 中的陷阱 6 錯誤

[英]Abort trap 6 error in 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 編譯它時,它很好。 當我運行該文件時,我在輸入值后收到 abort trap 6 錯誤。

我已經查看了有關此錯誤的其他帖子,但它們對我沒有幫助。

您正在寫入不屬於您的內存:

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];
合法指數是 board[0][0]...board[2][49]

編輯以解決錯誤的輸出注釋和初始化注釋

添加額外的 "\\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 to zero

數組初始化討論...

嘗試這個:

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");
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM