尝试填充一个二维数组,但它仍然是一个一维数组

try to fill a 2d array but it remains a 1d array C++

本文关键字:一个 仍然是 一维数组 二维数组 填充      更新时间:2023-10-16

我是编程新手,我试图填充一个简单的2d数组,但是当我测试代码时,它显示为一个具有我想要的2d数组的许多元素的1d数组。

void clearBoard(int row, int col) 
{
    int grid[row][col];
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col;j++) {
                grid[i][j] = 0;
                cout << grid[i][j] << " ";
            }
        }   cout << endl;
}
int main()
{
    int row1 = 2;
    int col1 = 2;
    //int _row = atoi(argv[0]);
    //int _col = atoi(argv[2]);
    //int _grid[5][5];
    //setBoard(row, col);
    //cout << "enter the size of the board:";
    //cin >> _row >> _col;
    clearBoard(row1, col1);

输出:

0 0 0 0 0

我要得到作为我的输出:

0 0 
0 0

你可以看到我把

注释掉了
int _row = atoi(argv[0]);
int _col = atoi(argv[2]);
cin >> _row >> _col;

是正确的方式来获得任何大小的数组?

谢谢。

cout << endl;移动到for循环中(它实际上不在其中),因为它目前将在没有新行的情况下打印所有结果,除非您将其移动到主for循环中:

注意:由于c++中的数组必须有一个常量大小,int grid[row][col]不能工作,因为row和col是非常量参数。

void clearBoard(int row, int col) 
{
    int grid[row][col]; 
    for (int i = 0; i < row; i++) 
    { 
        for (int j = 0; j < col;j++) 
        { 
            grid[i][j] = 0; cout << grid[i][j] << " ";     
        } 
        cout << endl;
    }
} 

固定大小错误的修复将使用std::vector<std::pair<int, int> >代替,虽然这将需要一些返工。

这是因为您在外部循环之后打印endl

改成:

        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col;j++) {
                grid[i][j] = 0;
                cout << grid[i][j] << " ";
            }
            cout << endl;  //Print newline after printing a row
        } 

是正确的方式来获得任何大小的数组?

不像Java,你可以在运行时声明数组的大小。在c++中,如果你想设置数组的大小,大小必须是一个常量。

你可以这样做:

const int rows = 5;
const int cols = 5;