【发布时间】:2020-01-11 04:51:33
【问题描述】:
程序
#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;
int main(int argc, char** argv)
{
if(argc < 2)
exit(1);
cout<<strtof(argv[1],NULL);
int SIZE = (int) (strtof(argv[1],NULL)/8);
int **arr = new int[SIZE][SIZE*4]();
for(int i = 0; i < SIZE; i++) {
for(int j = 0; j < SIZE*4; j++) {
cout<<arr[i][j];
}
}
return 0;
}
输入
32
错误
prog.cpp: In function ‘int main(int, char**)’: prog.cpp:13:39: error: array size in new-expression must be constant
int **arr = new int[SIZE][SIZE*4]();
^
prog.cpp:13:39: error: the value of ‘SIZE’ is not usable in a constant expression prog.cpp:12:9: note: ‘int SIZE’ is not const
int SIZE = (int) (strtof(argv[1],NULL)/8);
^~~~
除了在 C++11 中使用 malloc 或 calloc 之外,还有其他方法吗?
【问题讨论】:
-
使用
std::vector<std::vector<int>>。 -
可以创建 2D 动态数组,但向量更好,更易于使用。
-
绝对不是——将原始数组留给它们所属的 C。
-
这似乎是 936687 的直接复制品,是的。尽管我还没有阅读所有答案,但没有一个高分答案很好地涵盖了整个“矢量更好”的事情。
标签: c++ arrays c++11 command-line-arguments dynamic-memory-allocation