Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

assume that we created dynamically allocated memory such as:

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

it will assing 0 to 9 to our pointer array.
Then i wanted to add 10,11,12 to the array
can i do :

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

or should i do:

delete[] p;
size = 13;
p = new int[SIZE];
for(int i = 0; i < SIZE; ++i)
  p[i] = i;
like image 883
M.SEL Avatar asked Nov 18 '19 14:11

M.SEL


1 Answers

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.

like image 98
Vlad from Moscow Avatar answered Sep 27 '22 20:09

Vlad from Moscow