user2159166
user2159166

Reputation: 101

Dynamically allocating memory for changing array size starting with unknown size C++

How do I dynamically allocate an array where the size will be changing because the stuff stored in the array will be read from a file. There are lots of suggestions on using a vector, but I want to know how to do it the array way.

I know for memory allocation it is

int count;
int *n = new int[count];

Say the variable count is going to increment in a loop. How would I change the size of the array?

Also, what if we did it using malloc?

Upvotes: 1

Views: 5425

Answers (3)

Columbo
Columbo

Reputation: 61009

How would I change the size of the array?

Using new: You can't. The size of an object (here, an array object) can't change at runtime.

You would have to create a new array with the appropriate size, copy all elements from the old into the new array and destroy the old one. To avoid many reallocations you should always allocate more than you need. Keep track of the size (the amount of elements currently in use) and the capacity (the actual size of the allocated array). Once you want to increase the size, check whether there is still some memory left (size<capacity) and use that if possible; otherwise, apply the aforementioned method.

And that's exactly what vector does for you: But with RAII and all the convenience possible.

Upvotes: 1

Dr. Debasish Jana
Dr. Debasish Jana

Reputation: 7128

You may keep two pointers, p and q(placeholder), when count changes, you need to do a fresh allocation for p, before that earlier allocations need to be deallocated, even before that the contents of earlier p should be transferred to new p as well.

int count, oldcount;
int *p = NULL;
int *q;
p = new int[count];
oldcount = count;

when you need to re-allocate:

q = new int[count];
memcpy(q, p, oldcount * sizeof(int)); // OR for (int i = 0; i < oldcount; i++) q[i] = p[i];   
delete [] p;
p = q;
oldcount = count; // for use later

If you use malloc, calloc then you need to use as number of bytes to pass in malloc. but not needed with new and delete operators in C++

Upvotes: 2

mrjoltcola
mrjoltcola

Reputation: 20862

Don't try to make the array allocation exactly follow the continual changing size requirements of what you are going to store. Consider using the traditional 2*N multiple. When array is full, reallocate by growing by 2*N (allocate a new array twice as large), and copy items over. This amortizes the reallocation cost logarithmically.

Keep in mind that this logic you are setting out to implement with low level arrays is exactly why vector exists. You are not likely to implement your own as efficiently, or as bug free.

But if you are set on it, keep count a multiple of 2, starting with something realistic (or the nearest multiple of 2 rounded up)

Upvotes: 3

Related Questions