首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何通过命令行参数在C++11中创建大小为大小的动态数组?

如何通过命令行参数在C++11中创建大小为大小的动态数组?
EN

Stack Overflow用户
提问于 2019-09-09 12:05:33
回答 1查看 370关注 0票数 1

程序

代码语言:javascript
复制
#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

错误

代码语言:javascript
复制
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代码

EN

回答 1

Stack Overflow用户

发布于 2019-09-09 13:50:10

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

代码语言:javascript
复制
#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;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57853703

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档