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
.