Reputation: 2470
int a;
cin >> a;
int n[a];
When I used Visual Studio the program did not compile and reported an error. But when I used terminal to compile the program ran without any issues. Why is it so? And is this considered dynamic memory allocation ?
Upvotes: 3
Views: 109
Reputation: 1
No. This is not legal in C++11 or C++14. You are using an extension, called variable length array (that some, but not all, compilers provide).
Also, VLA don't work well for huge arrays - e.g. of several million components -, because in practice your call stack is limited (e.g. to a megabyte or a few of them)
Dynamic memory allocation is internally using something like new
(or malloc
). It changes the virtual address space of your process (thru system calls like mmap on Linux, which would be sometimes called by new
; on Windows something different is used.).
A good (and standard conforming) way to use dynamic memory would be to use some standard container, like std::vector
. Its data would be heap allocated (and released by the vector's destructor).
Upvotes: 10