Alright, the above is taken from cplusplus tutorial, it shows that foo is a pointer pointing to the 1st int which is int[0]. The program then allocates 5 memory space for 5 int. But what if instead of 'int [5]' i use 'int []' instead?
Below is a sample code which i wrote and i tried using both 'new int [2]' and 'new int []', there's no error etc and both results are the same. Would appreciate if someone could enlighten me on the difference between these 2. Thanks.
It really surprised me that statement like "int *i=new int[];" can be compiled without an error.
OK, I tried this code to find what happened.
The only thing I found at last is that this statement would actually return an address without calling the constructor. But I'm still confused about the size of the memory allocated from the heap by this statement.
By the way, I am using VS2010 to compile this code.
class Object{
public:
Object() { std::cout << "Constructed.\n"; }
};
int main()
{
Object *ptr = new Object[];
ptr[0] = Object();
ptr[1] = Object();
return 0;
}
Hmm ok.. I get it.. But I understand people use new int[2] as it can be created at run time right?
What then is the diff between
int i[2] and int *i = new int[2]?
I understand the first is an array, and the second is also an array but with pointer i pointing at the first object. But then why do we have these 2 way of doing array and when do we use which?
That creates a local array that is automatically destroyed when it goes out of scope.
int* x = newint[2];
This creates an array on the heap that has a lifetime for as long as you need it (it is never automatically destroyed... it is only destroyed when you delete[] it).
Also... the standard does not allow you create a local array with a variable size. The size has to be known at compile time. However, for heap arrays, you can have a variable size. So:
1 2 3 4
int size = getSomeValueFromUser();
int* foo = newint[size]; // Ok
int bar[size]; // Not ok (though some compilers may allow it anyway... others might error)
when do we use which?
Use the local array when you just need a small array for use in a function... or if you need a reasonably small, fixed-size array.
Use the 'new' version... well... never. Manual memory management in C++ should be avoided. There are usually better alternatives.
Both have the advantage of automatically cleaning up. Vector also has the advantage of being resizable (so if you need the array to grow or shrink, just call .resize() with a new size and vector will add/remove elements to the end to accommodate the new size).