[英]How to init dynamic array of pointers to nullptr c++
I have a code:我有一个代码:
var *item[8] = { nullptr };
and it works good.而且效果很好。 But i need to do this dynamically.
但我需要动态地做到这一点。 This is what i tried:
这是我尝试过的:
int n = 8;
var **item;
item = new var*[n]();
item = { nullptr };
but this is not working.但这不起作用。 Where is the difference and what should i do?
区别在哪里,我该怎么办?
//Sorry for my english //对不起我的英语不好
The ()
in item = new var*[n]();
item 中的
()
item = new var*[n]();
willvalue-initialize all of the pointers to nullptr
for you, so you don't need to do it manually afterwards.将为您初始化所有指向
nullptr
的指针,因此您无需在之后手动执行此操作。
int n = 8;
var **item;
item = new var*[n](); // <-- all are nullptr here
That said, you really should be using std::vector
instead of new[]
directly:也就是说,您确实应该直接使用
std::vector
而不是new[]
:
int n = 8;
std::vector<var*> item;
item.resize(n);
Or simply:或者简单地说:
int n = 8;
std::vector<var*> item(n);
Either way should initialize the pointers to nullptr
as well.无论哪种方式都应该初始化指向
nullptr
的指针。 But if you want to be explicit about it, you can do so:但是,如果您想明确说明,可以这样做:
int n = 8;
std::vector<var*> item;
item.resize(n, nullptr);
int n = 8;
std::vector<var*> item(n, nullptr);
if you have an array, vector or a container in general and you want to fill it with some value whichever that is you can use the std::fill function:如果你有一个数组、向量或一个容器,并且你想用一些值填充它,你可以使用 std::fill function:
std::fill(item,item+n,nullptr);
However if you want to assign nullptr at initialization time, it is much easier: you use zero initialization and you are fine.但是,如果您想在初始化时分配 nullptr,则要容易得多:使用 零初始化就可以了。 Just be aware of the difference between zero and default initialization:
请注意零初始化和默认初始化之间的区别:
item = new var*[n]{}; //zero initialized (all elements would have nullptr as value)
item = new var*[n]; //default initialized (elements might not have nullptr as value)
item = new var*[n](); //default initialized until C++03
//zero initialized after C++03
Anyway, I would suggest you to migrate to std::vector instead of C style arrays.无论如何,我建议您迁移到 std::vector 而不是 C 风格的 arrays。 You generally end up with much less error-prone code.
您通常会得到更少容易出错的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.