Use new operator to initialise an array

穿精又带淫゛_ 提交于 2019-12-09 04:37:29

问题


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 ?


回答1:


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};



回答2:


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.



来源:https://stackoverflow.com/questions/9603696/use-new-operator-to-initialise-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!