当我打印检查时,不确定为什么for循环不会在2D数组中保存正确的值。有什么想法吗?
#include <iostream>
using namespace std;
int row, col;
int main()
{
int num;
int val[row][col];
cout << "How many rows are there?" << endl;
cin >> row;
cout << "How many columns are there?" << endl;
cin >> col;
cout << "Enter values for the matrix: " << endl;
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
cin >> val[i][j];
}
}
return 0;
}
答案 0 :(得分:3)
#include <iostream>
using namespace std;
int main()
{
int row, col;
cout << "How many rows are there?" << endl;
cin >> row;
cout << "How many columns are there?" << endl;
cin >> col;
cout << "Enter values for the matrix: " << endl;
// check if row and col > 0
int* val = new int[row * col];
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
cin >> val[i * col + j];
}
}
delete[] val;
return 0;
}
答案 1 :(得分:1)
这不符合你的想法。
首先,row
和col
在程序启动时被初始化为零。然后你有int val[row][col];
这是无效的C ++,而是一个C变长数组。由于此时row
和col
均为0,因此此数组的长度为零。
在循环中,您会读取一堆值,覆盖堆栈中的内容并导致未定义的行为。
您应该使用动态分配的内容,例如std::vector
或您选择的数学库中的适当矩阵类。通常不建议手动使用动态分配(按照Ali建议的new int[row * col]
),因为这样很容易导致内存泄漏,尤其是涉及异常时。
答案 2 :(得分:0)
如果在C ++中支持可变长度数组,你可以通过移动来编写你想要的东西:
int val[row][col];
到已知行和列的位置。 查看这篇文章: build-tool-mode 否则您的代码具有未定义的行为。你应该使用动态分配。
答案 3 :(得分:0)
首先,你不能
int val[row][col];
在row和col之前具有已知值。其次,这种2D阵列初始化只是C中的标准。
您需要使用C ++运算符new []手动在堆上分配数组(类似于C中的malloc函数)。然而,这不是惯用的C ++,语言的全部意义在于避免这样做,这就是为什么我不能解释如何做到这一点。
正确的C ++实现你想要的方法是使用std :: vector,这是一个非常强大的C风格数据包装器,可以为你自动分配和解除内存(以及许多其他事情)。 / p>
这是最简单的方法:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int row;
cout << "How many rows are there?" << endl;
cin >> row;
int col;
cout << "How many columns are there?" << endl;
cin >> col;
int num;
cout << "Enter values for the matrix: " << endl;
cin >> num;
vector<vector<int>> values(col); //initialize outer vector with col inner vectors
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
values[i].push_back(num);
}
}
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
cout << values[i][j];
}
cout << endl;
}
return 0;
}
另外,我建议你用更多的含义命名你的变量,并避免使用命名空间std。
编辑:从您接近该计划的方式来看,我在答案中假设您熟悉C.如果情况并非如此,并且您正在阅读一本书或教程,那么您应该找到一个更好的书或教程。