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 ?
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.
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.
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.
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.
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.
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};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With