Looking at this example code, can someone tell me what the difference is if we eliminated the pointer *p and after the line "cin>>i" simply replaced "p=new..." with "int p[i]"? Both produce the same output? Thanks for the help!
// rememb-o-matic
#include <iostream>
#include <new>
using namespace std;
int main ()
{
int i,n;
int * p;
cout << "How many numbers would you like to type? ";
cin >> i;
p= new (nothrow) int[i];
if (p == 0)
cout << "Error: memory could not be allocated";
else
{
for (n=0; n<i; n++)
{
cout << "Enter number: ";
cin >> p[n];
}
cout << "You have entered: ";
for (n=0; n<i; n++)
cout << p[n] << ", ";
delete[] p;
}
return 0;
}
Thank you for the reply. However, I'm still a bit confused. You say int p[] requires a constant? So what would be the difference between these two snippets of code:
Thanks again for the help!
**************CODE 1***************
#include <iostream>
#include <new>
using namespace std;
int main ()
{
int i,n;
int * p;
cout << "How many numbers would you like to type? ";
cin >> i;
p= new (nothrow) int[i];
***************CODE 2***************
#include <iostream>
#include <new>
using namespace std;
int main ()
{
int i,n;
cout << "How many numbers would you like to type? ";
cin >> i;
int p[i];
The number of elements in a named array must be known at compile time. Therefore, it must be a constant value (either a const int or an integer literal).
Ok, well that still kind of helps. So normally, and to be safe, you should use dynamic memory allocation when you're trying to define something like an array after the program has begun execution?
Also, I am following the tutorial. The CODE 1 snippet is from the last program entitled "rememb-o-matic", in the tutorial on Dynamic Memory. However, I replaced the CODE 1 snippet with the CODE 2 snippet and the program still ran and produced the same results.
I'd still like to know why Dev is letting it compile and run.
Thanks for the help though. That actually cleared up a lot of my confusion.
I'd still like to know why Dev is letting it compile and run.
Because g++ (which is the compiler that comes with it) allows this as an extension.
It won't work with some other compilers and is not part of the C++ standard. However, it is part of the C standard, which is probably why g++ supports it too.