你如何在 C++ 中初始化一个动态数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2029651/
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
How do you initialise a dynamic array in C++?
提问by tgh
How do I achieve the dynamic equivalent of this static array initialisation:
如何实现此静态数组初始化的动态等效项:
char c[2] = {}; // Sets all members to 'char* c = new char[length]; // how do i amend this?
';
In other words, create a dynamic array with all values initialised to the termination character:
换句话说,创建一个动态数组,其中所有值都初始化为终止字符:
char* c = new char[length]();
回答by Fred
char *c = new char[length];
std::fill(c, c + length, INITIAL_VALUE);
// just this once, since it's char, you could use memset
回答by Steve Jessop
Two ways:
两种方式:
std::vector<char> c(length, INITIAL_VALUE);
Or:
或者:
std::vector<char> c(length);
In my second way, the default second parameter is 0 already, so in your case it's unnecessary:
在我的第二种方式中,默认的第二个参数已经是 0,所以在你的情况下它是不必要的:
char* c = new char[length];
std::fill_n(c,length,0);
[Edit: go vote for Fred's answer, char* c = new char[length]();
]
[编辑:去投票给弗雷德的答案,char* c = new char[length]();
]
回答by mrkj
Maybe use std::fill_n()
?
也许用std::fill_n()
?
char* c = new char[length]{};
char* d = new char[length]{ 'a', 'b', 'c' };
回答by AnT
The array form of new-expression accepts only one form of initializer: an empty ()
. This, BTW, has the same effect as the empty {}
in your non-dynamic initialization.
new 表达式的数组形式只接受一种形式的初始化器:空的()
。顺便说一句,这与{}
非动态初始化中的空值具有相同的效果。
The above applies to pre-C++11 language. Starting from C++11 one can use uniform initialization syntax with array new-expressions
以上适用于 C++11 之前的语言。从 C++11 开始,可以使用带有数组新表达式的统一初始化语法
std::vector <char> v( 100, 42 );
回答by AnT
C++ has no specific feature to do that. However, if you use a std::vector instead of an array (as you probably should do) then you can specify a value to initialise the vector with.
C++ 没有特定的功能来做到这一点。但是,如果您使用 std::vector 而不是数组(您可能应该这样做),那么您可以指定一个值来初始化向量。
char* c = new char[length];
memset(c, 0, length);
creates a vector of size 100 with all values initialised to 42.
创建一个大小为 100 的向量,所有值都初始化为 42。
回答by Thomas Bonini
You can't do it in one line easily. You can do:
您不能轻松地在一行中完成。你可以做:
void *operator new(size_t size, bool nullify)
{
void *buf = malloc(size);
if (!buf) {
// Handle this
}
memset(buf, 'char* c = new(true) char[length];
', size);
return buf;
}
Or, you can overload the new operator:
或者,您可以重载 new 运算符:
char* c = new char[length];
Then you will be able to do:
然后你将能够做到:
char* c = new char[length]{};
while
尽管
char* c = new char[length];
for(int i = 0;i<length;i++)
c[i]='##代码##';
will maintain the old behavior. (Note, if you want all new
s to zero out what they create, you can do it by using the same above but taking out the bool nullify
part).
将保持旧的行为。(请注意,如果您希望所有new
s 都将它们创建的内容归零,您可以使用上面相同的方法但取出bool nullify
部分来实现)。
Do note that if you choose the second path you should overload the standard new operator (the one without the bool) and the delete operator too. This is because here you're using malloc()
, and the standard says that malloc()
+ delete
operations are undefined. So you have to overload delete
to use free()
, and the normal new to use malloc()
.
请注意,如果您选择第二条路径,您应该重载标准的 new 操作符(没有 bool 的操作符)和 delete 操作符。这是因为您在这里使用malloc()
,并且标准说malloc()
+delete
操作未定义。所以你必须重载delete
才能使用free()
,而正常的 new 才能使用malloc()
。
In practice though all implementations use malloc()/free() themselves internally, so even if you don't do it most likely you won't run into any problems (except language lawyers yelling at you)
实际上,尽管所有实现都在内部使用 malloc()/free(),因此即使您不这样做,也很可能不会遇到任何问题(语言律师对您大喊大叫除外)
回答by songyuanyao
Since c++11 we could use list initialization:
从 c++11 开始,我们可以使用列表初始化:
##代码##For an aggregate type, then aggregate initializationwill be performed, which has the same effect like char c[2] = {};
.
对于聚合类型,则将执行聚合初始化,其效果与char c[2] = {};
.
回答by pm100
and the implicit comment by many posters => Dont use arrays, use vectors. All of the benefits of arrays with none of the downsides. PLus you get lots of other goodies
以及许多海报的隐含评论 => 不要使用数组,使用向量。具有数组的所有优点,但没有任何缺点。另外你会得到很多其他的好东西
If you dont know STL, read Josuttis The C++ standard library and meyers effective STL
如果您不了解 STL,请阅读 Josuttis The C++ 标准库和 meyers Effective STL
回答by Seva Alekseyev
No internal means, AFAIK. Use this: memset(c, 0, length);
没有内部手段,AFAIK。使用这个: memset(c, 0, length);
回答by almathie
you have to initialize it "by hand" :
你必须“手动”初始化它:
##代码##