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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With