1

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.

trincot
  • 317,000
  • 35
  • 244
  • 286
Leonardo
  • 1,452
  • 3
  • 15
  • 26

2 Answers2

6

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.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
-1

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.

paper.plane
  • 1,201
  • 10
  • 17
  • Line 3 does not make any sense to me. – Leonardo Mar 13 '13 at 08:28
  • -1 This changes the semantics a lot and will incur a significant performance penalty. – Alex Chamberlain Mar 13 '13 at 08:28
  • @AlexChamberlain it was just a work around, of course performance overheads are there, and vector is recommended. – paper.plane Mar 13 '13 at 09:02
  • @Alex Chamberlain the question wasnt about performance, it is not important here, over-pre-optimization : evil of everything – 4pie0 Mar 13 '13 at 10:04
  • @cf16 Well, let's be sensible. Pre-optimisation is bad, but you have 2 options on the table: allocate a new array and copy or fiddle around with an array of arrays. The first is both easier and more performant in most cases. Besides, the solution here was to use a vector. – Alex Chamberlain Mar 13 '13 at 11:00