Dynamic memory for n00bs

I'm trying to ge tto grips with dynamic memory allocation, and I'm a bit confused. What is the difference between this:

1
2
3
int c;
std::cin >> c;
int b[c];


and this?

1
2
3
4
int c;
std::cin >> c;
int * b = new int[c];
delete(b);


Fafner
In the first the compiler automatically gives the memory back to the system. In the second you have to do it yourself.
Both examples contain an error, by the way.
You must declare an automatic array with a size that is a constant known at compile-time.
The second example compiles, but is also wrong. You have to delete an array that was created with new[] using delete[].
Last edited on
Another difference is that the first allocates memory on the stack while the second does it on the heap. Also, the first is not standard c++ code. Not all compilers support it.
In the first you should write for example:

int b[4];

or:

1
2
enum NEW_TYPE {ONE=1, TWO=2, THREE=3, FOUR=4};
int b[FOUR];


I don't know if any compiler supports what you wrote (I mean first part).
Last edited on
Thanks all! The thing is that they both compile and run exactly the same way, which is why I asked in the first place. I find this weird, now that I've read your comments, but it's true nevertheless.

Fafner

EDIT: Using gcc btw
Last edited on
I've never even seen that first code snippet :P
fafner wrote:
Using gcc btw

That's why the first example works.

http://gcc.gnu.org/onlinedocs/gcc-2.95.3/gcc_4.html#SEC75
It's "officially" allowed to do that in C since the C99 standard, so it is no longer an extension for C...
but for C++ it remains an extension and so it might not work with other compilers (most notably VC++, which is a popular compiler in Windows environments).
Ah, I see! Excellent, thanks everybody;)
Topic archived. No new replies allowed.