【问题标题】:How to create a dynamic array in C++11 with size from command line arguments?如何在 C++11 中使用命令行参数的大小创建动态数组?
【发布时间】: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 之外,还有其他方法吗?


Code in Ideone

【问题讨论】:

  • 使用std::vector&lt;std::vector&lt;int&gt;&gt;
  • 可以创建 2D 动态数组,但向量更好,更易于使用。
  • 绝对不是——将原始数组留给它们所属的 C。
  • 这似乎是 936687 的直接复制品,是的。尽管我还没有阅读所有答案,但没有一个高分答案很好地涵盖了整个“矢量更好”的事情。

标签: c++ arrays c++11 command-line-arguments dynamic-memory-allocation


【解决方案1】:

如果你真的不想使用vector,那么这个工作代码可能会有所帮助。

#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];

    for(int i = 0; i < SIZE; i++) {
        arr[i] = new int[ 4* SIZE];
    }

    for(int i = 0; i < SIZE; i++) {
        for(int j = 0; j < SIZE*4; j++) {
            cout<<arr[i][j];
        }
    }

    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-13
    • 2013-06-07
    • 2013-05-08
    • 1970-01-01
    • 2012-11-27
    • 1970-01-01
    • 2016-12-21
    • 2023-03-31
    相关资源
    最近更新 更多