1

For some reason, even though I've looked and made myself as sure as I can be I'm doing this right, I keep getting exit status -1 in this code. I'm simply trying to create a dynamic 2d array and to fill each value with a 0:

Grid::Grid(int _rows, int _cols){

    Grid::rows = _rows;
    Grid::cols = _cols;

    Grid::grid = new int*[Grid::rows];

    for(int i = 0; i < Grid::rows; i++){

        Grid::grid[i] = new int[Grid::cols];

    }

    for(int i = 0; i < 1; i++){

        for(int j = 0; j < 1; i++){

            Grid::grid[i][j] = 0;

        }

    }
}

I've done some testing and the code runs fine without the second for loop when I'm trying to fill the array, so I think the problem is there, even though I can't see what would be wrong with it.

Here's the class just in case:

class Grid{

    private:

    int rows;
    int cols;
    int** grid;

    public:

    Grid(int _rows, int _cols);
    int getRows(){return rows;}
    int getCols(){return cols;}
    int** getGrid(){return grid;}
    void deleteArray();

};

I'm new to c++, so go easy on me if it's an obvious mistake. Thanks for the help.

3 Answers3

1

I'm afraid you haven't looked very hard

for(int i = 0; i < 1; i++){

    for(int j = 0; j < 1; i++){

        Grid::grid[i][j] = 0;

    }

}

should be

for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
        grid[i][j] = 0;
    }
}

You were incrementing the wrong variable in your inner loop (which meant it would have looped for ever). And for some reason you had a limit of 1 on your loops instead of rows and cols.

And there is no need to prefix your member variables with Grid::.

john
  • 85,011
  • 4
  • 57
  • 81
0

Congrats, your code works fine. The only problem is you have made a typo.

for(int i = 0; i < 1; i++){

    for(int j = 0; j < 1; j++){ //previously was i++

        Grid::grid[i][j] = 0;

    }

}

Also, you have used static limit "1". which can throw an error if rows/cols are less than 1.

priojeet priyom
  • 899
  • 9
  • 17
0

Your specific problem is simple to solve. You increment the wrong variable in the inner for-loop

for(int i = 0; i < Grid::rows; i++){ // loop over all elements

    for(int j = 0; j < Grid::cols; j++){ // j++ NOT i++ // also loop over all elements

        Grid::grid[i][j] = 0;

    }

}

My advice here is to use longer variable names, which differ more.

for(int idx_row = 0; idx_row < Grid::rows; ++idx_row){

    for(int idx_col = 0; idx_col < Grid::cols; idx_col++){

        Grid::grid[idx_row][idx_col] = 0;

    }

}
skratchi.at
  • 1,151
  • 7
  • 22