首页 文章

C中止陷阱6错误

提问于
浏览
17

我有这个代码:

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 回答

  • 1

    试试这个:

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

    你写的是你不拥有的记忆:

    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
    }
    ...
    

    Initialize 董事会变量:

    int board[3][50] = {0};//initialize all elements to zero
    

    array initialization discussion...

相关问题