Is it possible to create an array on the heap at r

2019-08-10 20:20发布

Lets say I do

char *a;
a = new char[4];

Now, is it possible to extend the size of the array further?

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++?


At first I felt like maybe I could just make:

char* a[10];
a[0] = new char[size];

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.

2条回答
时光不老,我们不散
2楼-- · 2019-08-10 20:51

Instead of char* a , you can use char** a;

i.e.

char**  a = new char*[4];

for(int i=0; i<4; i++)
  (*a)[i] = new char(i);   /* feed values to array */

/* now you need a[4]? no problem */
char tmp = (*a)[3];
a[3] = new char[2];

a[3][0] = tmp;
a[3][1] = xyz;    /* this is you a[4] */

Though this is a work around, I would suggest to used vector.

查看更多
女痞
3楼-- · 2019-08-10 20:52

Unfortunately it's not possible in C++. You have to allocate a new area and copy the old into the new.

However, C++ have other facilities, like std::vector, that alleviates the need to manually handle these things.

登录 后发表回答