0

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};
3
  • 6
    One isn't an array and one is Commented Aug 17, 2015 at 14:05
  • 2
    Best would be to use a std::vector or std::array. Raw arrays are significantly harder to use correctly. Commented Aug 17, 2015 at 14:55
  • @AlanStokes, make that an answer. We all need to encourage more vector use when beginners ask about C arrays. Commented Aug 17, 2015 at 19:00

3 Answers 3

4

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)

Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.