I was reading about dynamic memory allocation and static memory allocation and found the following about dynamic memory allocation:
In the programs seen in previous chapters, all memory needs were determined before program execution by defining the variables needed. But there may be cases where the memory needs of a program can only be determined during runtime. For example, when the memory needed depends on user input.
So I wrote the following program in C++:
#include <iostream>
int main()
{
int n = 0;
int i = 0;
std::cout << "Enter size: ";
std::cin >> n;
int vector[n];
for (i=0; i<n; i++)
{
vector[i] = i;
}
return 0;
}
This program works. I don't understand how it works. When is the size determined here? How does the vector get allocated in this case?
Dynamic memory allocation is the process of assigning the memory space during the execution time or the run time. Reasons and Advantage of allocating memory dynamically: When we do not know how much amount of memory would be needed for the program beforehand.
Unlike a fixed array, where the array size must be fixed at compile time, dynamically allocating an array allows us to choose an array length at runtime. Because we are allocating an array, C++ knows that it should use the array version of new instead of the scalar version of new.
Dynamically allocated arrays are allocated on the heap at run time. The heap space can be assigned to global or local pointer variables that store the address of the allocated heap space (point to the first bucket).
According to this (emphasis mine):
Variable-length automatic arrays are allowed in ISO C99, and as an extension GCC accepts them in C90 mode and in C++. These arrays are declared like any other automatic arrays, but with a length that is not a constant expression. The storage is allocated at the point of declaration and deallocated when the block scope containing the declaration exits.
Note that this is just an extension and won't work on every compiler, for instance it doesn't work for me in MSVC (I get the error "expression must have a constant value").
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