我正在尝试通过以下方式从命令行输入分配数组。但我仍然收到警告。将错误消息粘贴在下面。请查看它。哪些更改可以使此代码完美。
int ni = atoi(argv[1]);
int nj = atoi(argv[2]);
int *a[ni][nj];
for(i=1; i<ni; i++)
{
for(j=1; j<nj; j++)
{
a[i][j] = 10*j + i;
}
printf("%d", a[i][j]);
}
编译器输出:
In function main:
warning: incompatible implicit declaration of built-in function malloc
warning: assignment makes pointer from integer without a cast
最佳答案
由于您使用的是 C++,因此我建议采用以下方式:
#include <vector>
#include <iostream>
// ...
int ni = atoi(argv[1]);
int nj = atoi(argv[2]);
std::vector< vector<int> > a(ni, vector<int>(nj));
for (int i = 0; i<ni; i++)
{
for (int j = 0; j<nj; j++)
{
a[i][j] = 10 * j + i;
std::cout << a[i][j];
}
}
关于c++ - 从命令行输入分配二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21897380/