如何初始化大小最初未知的数组? [英] How to initialize an array whose size is initially unknown?

查看:381
本文介绍了如何初始化大小最初未知的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有这个:

int x;
int x = (State Determined By Program);
const char * pArray[(const int)x]; // ??

在使用pArray之前,我该如何初始化它? 因为Array的初始大小是由用户输入决定的

How would I initialize pArray before using it? Because the initial size of the Array is determined by user input

谢谢!

推荐答案

如果要在运行时确定大小,则无法在编译时初始化数组.

You cannot initialize an array at compile-time if you are determining the size at run-time.

但是根据您要执行的操作,指向const数据的非const指针可能会为您提供所需的信息.

But depending on what you are trying to do, a non-const pointer to const data may provide you with what you're going for.

const char * pArray = new const char[determine_size()];

更完整的示例:

int determine_size()
{
    return 5;
}

const char * const allocate_a( int size )
{
    char * data = new char[size];
    for( int i=0; i<size; ++i )
        data[i] = 'a';
    return data;
}

int main()
{
    const char * const pArray = allocate_a(determine_size());
    //const char * const pArray = new char[determine_size()];
    pArray[0] = 'b'; // compile error: read-only variable is not assignable 
    pArray    =  0 ; // compile error: read-only variable is not assignable 

    delete[] pArray;
    return 0;
}

我确实同意其他人的观点,即std :: vector可能更是您想要的东西.如果您希望它的行为更像const数组,则可以将其分配给const引用.

I do agree with others that a std::vector is probably more what you're looking for. If you want it to behave more like your const array, you can assign it to a const reference.

#include <vector>

int main()
{
    std::vector<char> data;
    data.resize(5);

    const std::vector<char> & pArray = data;

    pArray[0] = 'b'; // compile error: read-only variable is not assignable
}

这篇关于如何初始化大小最初未知的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆