C++动态数组的初始值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10294801/
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
c++ initial value of dynamic array
提问by Arno
I need to dynamically create an array of integer. I've found that when using a static array the syntax
我需要动态创建一个整数数组。我发现使用静态数组时,语法
int a [5]={0};
initializes correctly the value of all elements to 0.
将所有元素的值正确初始化为 0。
Is there a way to do something similar when creating a dynamic array like
创建动态数组时有没有办法做类似的事情
int* a = new int[size];
without having to loop over all elements of the a array? or maybe assigning the value with a for loop is still the optimal way to go? Thanks
不必遍历数组的所有元素?或者用 for 循环分配值仍然是最佳方式?谢谢
回答by sharptooth
Sure, just use ()
for value-initialization:
当然,仅()
用于值初始化:
int* ptr = new int[size]();
(taken from this answerto my earlier closely related question)
(摘自这个回答我刚才的密切相关的问题)
回答by Robert
I'd do:
我会做:
int* a = new int[size];
memset(a, 0, size*sizeof(int));
回答by Andrey
I'd advise you to use std::vector<int>
or std::array<int,5>
我建议你使用std::vector<int>
或std::array<int,5>
回答by Andreas DM
Value initialize the elements with ()
值初始化元素 ()
Example:
例子:
int *p = new int[10]; // block of ten uninitialized ints
int *p2 = new int[10](); // block of ten ints value initialized to 0
回答by THEOS
To initialize with other values than 0,
要使用 0 以外的其他值进行初始化,
for pointer array:
对于指针数组:
int size = 10;
int initVal = 47;
int *ptrArr = new int[size];
std::fill_n(ptrArr, size, initVal);
std::cout << *(ptrArr + 4) << std::endl;
std::cout << ptrArr[4] << std::endl;
For non pointer array
对于非指针数组
int size = 10;
int initVal = 47;
int arr[size];
std::fill_n(arr, size, initVal);
Works pretty Much for any DataType!
适用于任何数据类型!
!Be careful, some compilers might not complain accessing a value out of the range of the array which might return a non-zero value
!小心,一些编译器可能不会抱怨访问超出数组范围的值,这可能会返回非零值
回答by THEOS
int *a=new int[n];
memset(a, 0, n*sizeof(int));
That sets the all the bytes of the array to 0. For char *
too, you could use memset.
See http://www.cplusplus.com/reference/clibrary/cstring/memset/for a more formal definition and usage.
这char *
会将数组的所有字节设置为 0。同样,您可以使用 memset。有关更正式的定义和用法,请参阅http://www.cplusplus.com/reference/clibrary/cstring/memset/。