C++ how to add an element to a pointer array by exceeding size

You have to reallocate memory for the array of a greater size. Otherwise the program will have undefined behavior.

For example

int SIZE = 10;
int *p = new int[SIZE];
for(int i = 0; i < SIZE; ++i)
  p[i] = i;

int *tmp = new int[SIZE + 3];

std::copy( p, p + SIZE, tmp );
delete []p;
p = tmp;

p[SIZE++] = 10;
p[SIZE++] = 11;
p[SIZE++] = 12;

Or instead of the last three statements you can write

for ( const int &value : { 10, 11, 12 } ) p[SIZE++] = value;

Of course in such cases it is better to use the standard container std::vector.

In fact the code above is similar to the following

#include <vector>

//...

std::vector<int> v( 10 );

for ( int i = 0; i < v.size(); i++ ) v[i] = i;

v.reserve( 13 );
for ( const int &value : { 10, 11, 12 } ) v.push_back( value );

except that all the memory management is done internally by the vector.


The second option is the correct way. The first option won't always complain, but you are writing to memory that has not been set aside for your array; it has been set aside for something else, and you don't know what. Sometimes it will behave okay, sometimes it won't. Assigning to an array outside its range is Undefined Behavior, and we should avoid it.


In your first example suggestion:

p[10] = 10;
p[11] = 11;
p[12] = 12;

You will be overwriting memory that you don't own, which can lead to a crash. You need to reallocate your original array.

const int oldSize = SIZE;
SIZE = 13;
int *newP = new int[SIZE];
memcpy(newP, p, oldSize * sizeof(int));
for (int i = oldSize; i < SIZE; ++i)
{
    newP[i] = i;
}

delete[] p;
p = newP;

Your second example would work, but is slightly less efficient, because you're re-calculating the values with each reallocation. In my example above, you only re-calculate the new values.

Alternatively, you should look at std::vector which is designed specifically for this purpose (a dynamically sizing array).

std::vector<int> p;
for (int i = 0; i < 10; ++i)
{
    p.push_back(i);
}

Here the std::vector manages the allocation internally, so you don't have to worry about new and delete.