So I've always been told you should use dynamic memory when you don't know the size of the array at compilation time. For example, the user needs to input the size of the array.
int n;
cin >> n;
int array[n];
for(int ii = 0; ii < n; ii++)
{
array[ii] = ii;
}
for(int ii = 0; ii < n; ii++)
{
cout << array[ii] << endl;
}
However this works fine for me, I've always thought I would need to use a pointer and the new operator. Is dynamic memory then only for when you want to change size of the array, free up space, or having the ability to control when to release the memory? Thanks.
It works fine because it is an extension allowed by your compiler. It is not legal C++, and I'd recommend you avoid it. In order to help you avoid it, I recommend you compile with -pedantic to flag the usage of non-standard extensions as warnings, and -Werror to treat warnings as errors. Or with -pedantic-errors if you don't want to treat all warnings as errors, just warnings of this type.
But that doesn't mean you should be using a pointer and new. You should instead use std::vector. Or possibly std::deque or std::list, but only for very special purposes. For most general purpose dynamic arrays, std::vector is the choice.
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