C++ 使用 new 运算符初始化数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9603696/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Use new operator to initialise an array
提问by lilroo
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:
但是,我需要使用 new 运算符来分配内存,例如:
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 ?
有没有办法组合这些方法,以便我可以使用 new 运算符分配内存并使用花括号初始化数组?
采纳答案by Luchian Grigore
You can use memcpy
after the allocation.
memcpy
配置好后就可以使用了。
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};
回答by jogojapan
In the new Standard for C++ (C++11), you can do this:
在新的 C++ 标准 (C++11) 中,您可以这样做:
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.
包含更多详细信息(并且很难阅读)的相关在线参考资料在这里。我还使用 GCC 和--std=c++0x
选项进行了尝试,并确认它确实有效。