Abort trap 6 error in C

后端 未结 2 1500
别跟我提以往
别跟我提以往 2020-12-01 23:24

I have this code:

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 cou         


        
相关标签:
2条回答
  • 2020-12-02 00:03

    You are writing to memory you do not own:

    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';
              ^
    

    Change this line:

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

    To:

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

    When creating an array, the value used to initialize: [3] indicates array size.
    However, when accessing existing array elements, index values are zero based.

    For an array created: int board[3][50];
    Legal indices are board[0][0]...board[2][49]

    EDIT To address bad output comment and initialization comment

    add an additional "\n" for formatting output:

    Change:

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

    To:

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

    Initialize board variable:

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

    ( array initialization discussion... )

    0 讨论(0)
  • 2020-12-02 00:20

    Try this:

    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 讨论(0)
提交回复
热议问题