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
> 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++
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?
> 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.