M.S*_*SEL 7 c++ arrays pointers memory-management vector
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;
Run Code Online (Sandbox Code Playgroud)
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;
Run Code Online (Sandbox Code Playgroud)
or should i do:
delete[] p;
size = 13;
p = new int[SIZE];
for(int i = 0; i < SIZE; ++i)
p[i] = i;
Run Code Online (Sandbox Code Playgroud)
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;
Run Code Online (Sandbox Code Playgroud)
Or instead of the last three statements you can write
for ( const int &value : { 10, 11, 12 } ) p[SIZE++] = value;
Run Code Online (Sandbox Code Playgroud)
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 );
Run Code Online (Sandbox Code Playgroud)
except that all the memory management is done internally by the vector.