简体   繁体   English

如何在C ++ 11中使用命令行参数的大小创建动态数组?

[英]How to create a dynamic array in C++11 with size from command line arguments?

Program 程序

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

Input 输入项

32 32

Error 错误

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);
         ^~~~

Is there any other way, rather than using malloc or calloc to do this in C++11? 还有其他方法,而不是在C ++ 11中使用malloc或calloc做到这一点吗?


Code in Ideone Ideone中的代码

If you really don't want to use vector , then maybe this working code can help. 如果您真的不想使用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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM