I am a new C++ programmer but not new to programming (Matlab etc..). I am trying to understand the benefit of using "new" to get dynamic memory versus a standard array declaration. Please see my code below. Both work. So what is the advantage of using new? Thanks !
#include <iostream>
#include <string>
using namespace std;
int main()
{
//some previous code...
int true_false;
//dynamic memory using standard array declaration
cout << "Enter 1 for true, 0 for false\n";
cin >> true_false;
if (true_false==1)
{
cout << "true\n";
int arr_size=100;
int arr2[arr_size];
}
else
{
cout << "false\n";
}
//dynamic memory using the new pointer method
cout << "Enter 1 for true, 0 for false\n";
cin >> true_false;
if (true_false==1)
{
cout << "true\n";
int arr_size=100;
int* ip2=new int[arr_size];
//do something with allocated memory...
delete []ip2;
}
else
{
cout << "false\n";
}
return 0;
}
Unfortunately, I don't believe line 16 is valid C++. You can't plug a variable like that into the [ ] used for declaring an array. It has to be constant, although some compilers will support it.
To prove this, I copied and pasted your code into a C++ file, and compiled it using the flag -pedantic, which requires g++ to follow the ISO C++ standard exactly.
albatross$ g++ /Users/albatross/Documents/testpad/proof.cpp -pedantic
/Users/albatross/Documents/testpad/Complex.cpp: In function ‘int main()’:
/Users/albatross/Documents/testpad/Complex.cpp:16: error: ISO C++ forbids variable-size array ‘arr2’
I am using Code::Blocks IDE with the MinGW compiler. I will see if I can use something similar to the -pedantic flag to check my code for ISO compliance.
You should be able to add -pedantic somehow, hobbycoder. Code::Blocks does use g++ for compilation if included (albeit ported to Windows with a bunch of other stuff under the name, you guessed it, MinGW).
Unfortunately, I'm not extremely familiar with Code::Blocks, so I couldn't tell you how do make Code::Blocks invoke g++ with that flag, sorry. I'm sure there's a way, though.
Final note...In the build options I was indeed able to select the strict -pedantic -error option. So now the code gives
"Compiling: main.cpp
C:\Documents and Settings\sabhyank\My Documents\matlab_vba_c_dev\c_development\pointers\main.cpp: In function 'int main()':
C:\Documents and Settings\sabhyank\My Documents\matlab_vba_c_dev\c_development\pointers\main.cpp:35: error: ISO C++ forbids variable length array 'arr2'
C:\Documents and Settings\sabhyank\My Documents\matlab_vba_c_dev\c_development\pointers\main.cpp:35: warning: unused variable 'arr2'
Process terminated with status 1 (0 minutes, 0 seconds)
1 errors, 1 warnings"