I am trying to understand the difference between static and dynamic arrays in C++ and I can not think of a case where a static array would not do the trick.
I am considering a static array that would be declared this way:
int N=10;
int arr[N];`
I read here that the main difference between static and dynamic array is that a static array is allocated during compilation so N needs to be know at compilation.
However, this explains that arrays declared this way can also be Variable-length arrays:
Variable-length arrays were added in C99 - they behave mostly like fixed-length arrays, except that their size is established at run time; N does not have to be a compile-time constant expression:`
and indeed, the following c++ code is working, even though n
is only known at runtime :
int n =-1;
std::cin>>n;
int arr[n];
//Let the user fill the array
for(int i=0; i<n;i++){
std::cin>>arr[i];
}
//Display array
for(int i=0; i<n;i++){
std::cout<<i<<" "<<arr[i]<<std::endl;
}
So I would like an example of code were a static arrays defined like this would not work and the use of dynamic array would be required ?
The code doesn't work on all compilers because variable length arrays aren't part of C++. They are part of C as of ISO C99, and some compilers will allow VLAs in C++, but it's not a portable solution. GCC, for instance, allows VLAs, but warns the user (-Wno-vla
).
Below the hood, VLAs are dynamic anyway as the compiler can't reserve the appropriate amount of stack memory because it doesn't know how big the array is going to be. Instead of VLAs, std::vector
can be used for dynamic memory that gets deallocated at the end of the scope.