Welcome to HBH! If you have tried to register and didn't get a verification email, please using the following link to resend the verification email.

Can someone explain the difference here? (Dynamic Memory)


ghost's Avatar
0 0

I realize this is a very noobish question but can someone explain to me the difference between these two snippets of code?

The way I understand it, CODE 2 should not compile. However, under Dev C++, it compiles and runs fineā€¦.which makes me wonder why would you use CODE 1.

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];


ghost's Avatar
0 0

from my noobish point of view both pieces of code are fine. In c++ there is a dynamic memory allocation so np with that. In general you should use code 1. Code 2 is ok till you use value types when you use objects then you need code 1 and explicit constructor calls. In fact I may be wrong, please correct or delete my post if so.


ghost's Avatar
0 0

Ok. That clears a bit up then. Thanks


ghost's Avatar
0 0

Code 2 should according to old standards indeed not compile. However, certain compilers do offer that type of behaviour, though it shouldn't be allowed. If I recall correctly though, newer standards allow for it or they are at least planning on changing to allow code 2 as well. But, it'll basically result in the same thing as code 1, or at least should.