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
-pedanticto flag the usage of non-standard extensions as warnings, and-Werrorto treat warnings as errors. Or with-pedantic-errorsif 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 usestd::vector. Or possiblystd::dequeorstd::list, but only for very special purposes. For most general purpose dynamic arrays,std::vectoris the choice.