Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use new operator to initialise an array

I want to initialise an array in the format that uses commas to separate the elements surrounded in curly braces e.g:

int array[10]={1,2,3,4,5,6,7,8,9,10}; 

However, I need to use the new operator to allocate the memory e.g:

int *array = new int[10]; 

Is there a way to combine theses methods so that I can allocate the memory using the new operator and initialise the array with the curly braces ?

like image 342
lilroo Avatar asked Mar 07 '12 14:03

lilroo


People also ask

How do you initialize an array in new?

To use the array, we can initialize it with the new keyword, followed by the data type of our array, and rectangular brackets containing its size: int[] intArray = new int[10]; This allocates the memory for an array of size 10 . This size is immutable.

Is it necessary to use new operator to initialise an array?

JAVA Programming Array can be initialized when they are declared. Array can be initialized using comma separated expressions surrounded by curly braces. It is necessary to use new operator to initialize an array.

What is use of new operator in defining an array?

The new operator is used in Java to create new objects. It can also be used to create an array object. Declaration − A variable declaration with a variable name with an object type. Instantiation − The 'new' keyword is used to create the object.

How do you use the new operator?

Use of the new operator signifies a request for the memory allocation on the heap. If the sufficient memory is available, it initializes the memory and returns its address to the pointer variable. The new operator should only be used if the data object should remain in memory until delete is called.


2 Answers

In the new Standard for C++ (C++11), you can do this:

int* a = new int[10] { 1,2,3,4,5,6,7,8,9,10 }; 

It's called an initializer list. But in previous versions of the standard that was not possible.

The relevant online reference with further details (and very hard to read) is here. I also tried it using GCC and the --std=c++0x option and confirmed that it works indeed.

like image 116
jogojapan Avatar answered Oct 15 '22 04:10

jogojapan


You can use memcpy after the allocation.

int originalArray[] ={1,2,3,4,5,6,7,8,9,10}; int *array = new int[10]; memcpy(array, originalArray, 10*sizeof(int) ); 

I'm not aware of any syntax that lets you do this automagically.

Much later edit:

const int *array = new int[10]{1,2,3,4,5,6,7,8,9,10}; 
like image 43
Luchian Grigore Avatar answered Oct 15 '22 05:10

Luchian Grigore