是否可以在运行时在堆上创建一个数组,然后在需要时分配更多的空间? [英] Is it possible to create an array on the heap at run-time, and then allocate more space whenever needed?
问题描述
让我说
char *a;
a = new char[4];
现在,是否可以进一步扩展数组的大小?
Now, is it possible to extend the size of the array further?
说我想把 a [0] 中的任何值保留到
a [3]
但现在我想为 a [4]
和 a [5]
在C ++中?
Say I want to keep any values I put inside a[0]
to a[3]
but now I want more space for a[4]
and a[5]
etc. Is that possible in C++?
起初我觉得可能只是:
char* a[10];
a[0] = new char[size];
每当需要更多空间时,我可以转到 a [1] code>并分配更多空间。这是我目前唯一可以想到的选择。
Whenever more space is needed I can go to a[1]
and allocate more space. This is the only alternative I can think of at the moment.
推荐答案
不幸的是,在C ++中是不可能的。你必须分配一个新区域并将旧区域复制到新区域。
Unfortunately it's not possible in C++. You have to allocate a new area and copy the old into the new.
但是,C ++还有其他功能,例如 std :: vector
,这减轻了手动处理这些事情的需要。
However, C++ have other facilities, like std::vector
, that alleviates the need to manually handle these things.
这篇关于是否可以在运行时在堆上创建一个数组,然后在需要时分配更多的空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!