I know fixed-size arrays in C++ are allocated on the stack, and I know that a dynamic-sized array created using new[] keyword will be allocated on the heap.
But consider this snippet of code:
std::cout << "Enter a length of the array: "
int length{};
std::cin >> length;
int arr[length]{};
for (int i{ 0 }; i < length; ++i)
{
arr[i] = i;
std::cout << arr[i] << ' ';
}
std::cout << '\n'
It compiles without a problem. So am I right in assuming that such arrays are implicitly placed on the heap? And if so, how does it works, is the memory used by this array freed after implicitly too?
>Solution :
This is not standard C++.
The compiler you are using supports a mixture of C and C++ features in the same file. The support for variable-length arrays is a C feature.
Variable-length arrays are stored on the stack, typically. This is more or less equivalent to allocating the array with alloca().
(I recommend avoiding variable-length arrays. Since they are not part of C++, they may interact poorly with some C++ features, and most C++ compilers will not support them at all. You probably want to use std::vector instead.)