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.

2

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Or, if it doesn't need to be contiguous, std::deque can avoid reallocations.
Thanks, a vector sounds like what I will want to use for this program.
-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.

5 Comments

Line 3 does not make any sense to me.
-1 This changes the semantics a lot and will incur a significant performance penalty.
@AlexChamberlain it was just a work around, of course performance overheads are there, and vector is recommended.
@Alex Chamberlain the question wasnt about performance, it is not important here, over-pre-optimization : evil of everything
@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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.