Question
What is the most efficient way to add memory allocation to an already declared variable?
For example:
int n=3;
int m = 4;
int * p;
p = new int[n];
for(int i = 0;i<n;i++) {/*function that stores values in p*/}
From there, how to get to:
p = new int[n+m];
By copying
I've thought about making a new variable (y for example) with the required memory allocation (n+m) and copy the value of p to it and then copy y to p. Is that the most efficient way to do this ?
Example:
int * y;
y = new int[n + m];
for(int i = 0; i < n;i++) {y[i] = p[i];}
p = y;
delete [] y;
Related question:
Is there a purpose for memory allocation without an array?
Example:
int * p;
p = new int;
What would require this method instead of declaring int p
?