Dynamic Memory

Hi Folks,
I am just learning about dynamic memory. Can someone explain to me why the code below works without giving me n error? I declare an array (without the "new" keyword) whose size is not known until run time. I do not use dynamic memory allocation so why does the program work?
Thanks,
D.

#include <iostream>
using namespace std;

int main()
{
int num;
cout<<"Enter a number"<<endl;
cin>>num;

int myArray[num]; //Array size determined at run time

for(int i=0; i<num; i++)
cin>>myArray[i];

for(int i=0; i<num; i++)
cout<<myArray[i]<<endl;
}
> I declare an array (without the "new" keyword) whose size is not known until run time.
> I do not use dynamic memory allocation so why does the program work?

Your program works because, by default, the compiler that you are using is non-conforming in this respect.

You need to tell this compiler: "this is a C++ program; therefore compile it as C++ code".
You can do that by specifying the following compiler options:
-std=c++11 - this is a C++profgram
-pedantic-errors - generate errors for code that is not standard C++

Something like:
> g++ -std=c++11 -pedantic-errors -Wall -Wextra my_program.cpp
Thanks JLBorges.

I was using the -std=c++11 option but only received an error when I added the"-pedantic-errors" option.
I know you shouldn't use a variable length array but why not? The program compiles and runs fine and only displays an error when you add the -pedantic-errors option.

If it was an issue, I thought the g++ compiler (v4.7.2) would be much stricter than this and forbid you to even attempt to use a variable length array without allocating dynamic memory for it. Why is it so easy to do?
Last edited on
> I know you shouldn't use a variable length array but why not?

For one, this
int myArray[num] ; //Array size determined at run time
may fail (not enough memory) and there is no way to check for failure.

And what about sizeof(myArray) ?

Note: A saner form of variable length arrays with automatic storage duration may become available in the next C++ standard. http://isocpp.org/blog/2013/04/trip-report-iso-c-spring-2013-meeting


> I thought the g++ compiler (v4.7.2) would be much stricter than this
> and forbid you to even attempt to use a variable length array
> Why is it so easy to do?

In an ideal world, it wouldn't be; it harms people learning C++. The reasons are political rather than technical. Once you make a mistake, you continue making the same mistake for reasons of backward compatibility.

Every compiler vendor has a vested interest in trying to lock people into using their compiler. The easiest way to do this is to encourage the use of non-standard dialects; then the code won't compile with another conforming C++ compiler. So GNU has non-standard linuxisms enabled by default and Microsoft announces that std::strcpy() is deprecated.
Ok, I think I am starting to understand....thank you for taking the time to explain JLBorges.
Topic archived. No new replies allowed.