簡體   English   中英

如何在C ++ 11中使用命令行參數的大小創建動態數組?

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

程序

#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做到這一點嗎?


Ideone中的代碼

如果您真的不想使用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