简体   繁体   中英

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](); willvalue-initialize all of the pointers to nullptr for you, so you don't need to do it manually afterwards.

int n = 8;
var **item;
item = new var*[n](); // <-- all are nullptr here

Live Demo

That said, you really should be using std::vector instead of new[] directly:

int n = 8;
std::vector<var*> item;
item.resize(n);

Or simply:

int n = 8;
std::vector<var*> item(n);

Live Demo

Either way should initialize the pointers to nullptr as well. 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);

Live Demo

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(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. 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. You generally end up with much less error-prone code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM