0

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

2
  • This is a duplicate of stackoverflow.com/a/2615245/4045598. Commented Apr 22, 2020 at 23:09
  • 3
    Providing a value in the { } only initialises the first element. This is a common misconception, where people think bool arr[5] = { true }; will initialise them all to true Commented Apr 22, 2020 at 23:11

2 Answers 2

3

The () in item = new var*[n](); will value-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

Sign up to request clarification or add additional context in comments.

2 Comments

Just item = new var*[8](); works only with 8 entered in code. But when i put variable it doesn't work
@shumik_UA Works fine for me, and it is standard behavior. So if it is not initializing correctly for you then it is probably a compiler bug.
2

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.

1 Comment

Thanks, of course i prefer to use vector. But it's not allowed in this task

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.