What is better(more efficient) way of creating and initializing array ?
1. int array[3] {1,2,3};
2. int *array=new int[3]{1,2,3};
Don't assume that "better" always means more efficient! In a function body, these two do very different things:
int array[3] {1,2,3};
The first allocates local storage (on the stack) which will be released when the function terminates. (so you should not attempt to use it beyond that lifetime).
int *array = new int[3] {1,2,3};
The second allocates new heap memory, which will not be released when the function terminates. (so you should remember to delete[] it when it is no longer required)
The best way is:
int array[3] = {1,2,3}; // assignment operator added
In your examples only the 1st is array:
int array[3];
The second one is a pointer that assigned with address returned by operator new. To see the difference try sizeof(array) for both:
int array[3];
cout << sizeof(array) << endl;
with my compiler shows 12 (i.e. 3 * sizeof(int), size of array depends on number of elements ), but
int *array=new int[3];
cout << sizeof(array) << end
for my compiler shows 4 (i.e. sizeof(int*), size of pointer depends only from platform)
lets start with second one.
int *array = new int[3] {1,2,3};
It creates a dynamic array.'Dynamic' means that the memory will be allocated during the run-time and not while compiling.So your above initialization will create an array of size 3 and it will be initialized with the given values. Remember dynamic allocated memory has no predefined scope ,hence the memory needs to be released using 'delete' operator. Also be careful while using pointers ,as they may create havoc in your program if not used properly!
Now the first one.
int array[3] = {1,2,3};
It creates an array of size 3 and initializes it with the given values. And in this the memory is allocated statically(during compilation). As long as the program continues the variable stays in memory and then vanish! So you can decide the type of array initialization as per your requirement.
std::vectororstd::array. Raw arrays are significantly harder to use correctly.vectoruse when beginners ask about C arrays.