尝试填充一个二维数组,但它仍然是一个一维数组
try to fill a 2d array but it remains a 1d array C++
我是编程新手,我试图填充一个简单的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;
相关文章:
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 为什么需要知道一个类是平凡的还是有平凡的构造函数
- 检查一个类型是否直接派生自"enable if"上下文中的另一个类型(是其子类型)
- 在学习数据结构之前对STL有一个了解是好的吗?
- 在C++,重复申报仍然是一个问题吗?
- "Memory Fragmentation"这仍然是一个问题?
- 将基本类型数组中的内存重新用于不同(但仍然是基本)类型的数组合法吗
- 为什么 (-i) 的类型(其中 i 是无符号的 int)仍然是无符号的 int?
- 如何设计一个始终是另一个类的成员的类
- 更新 g++ 但仍然是旧版本
- 没有一个不是用NewObject,NewNamedObject或ConstructObject构建的,但它是
- boost_asio_handler_invoke_helpers::invoke 是否仍然是在 boost asio
- 是转发参考是否仍然是RVALUE参考
- 将结构编写为二进制,其中一个成员是字符串
- 找到一个总和是 10 倍数的数字
- 是shared_ptr的引用仍然是一个指针
- 强制构造像“Foo(12,3);”这样的未命名变量仍然是一个声明符
- 一个函数可以访问的类变量或成员函数中仍然是对象感知的静态变量
- 尝试填充一个二维数组,但它仍然是一个一维数组
- GMock将一个模拟对象传递给另一个对象,并调用一个stubed方法,这仍然是在调用真正的逻辑