C中止陷阱6错误

时间:2014-10-17 18:22:12

标签: c arrays loops abort

我有这段代码:

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 个答案:

答案 0 :(得分:27)

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

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]

编辑 解决错误的输出评论和初始化评论

添加额外的&#34; \ n&#34;用于格式化输出:

更改:

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

array initialization discussion...

答案 1 :(得分:0)

试试这个:

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