Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to fill array of pointers with NULL?

Tags:

c++

arrays

I have array of pointers:

private:
    LimitOrder* orders[Size];

In constructor i'm trying to fill it with NULL:

InternalIdAssigner::InternalIdAssigner(void):
    lastCleanId(0)
{
    std::fill(orders, orders + Size, NULL);

But this doesn't work, I receive error: error C2440: '=' : cannot convert from 'const int' to 'LimitOrder *'

What is the right way to fill array field with NULL?

like image 984
Oleg Vazhnev Avatar asked Oct 23 '25 14:10

Oleg Vazhnev


1 Answers

The error message is kind of clear, if you understand what NULL really is: a literal 0.

When you pass 0 to a template, the deduced type is int, not a pointer type. While a literal 0 is implicitly convertible to any pointer type and will be a null pointer, after it if passed to fill it is just an int with value 0, which is not convertible to a pointer type.

In C++11 you could and should use nullptr instead of NULL. In C++03 you can also convert the pointer to the destination type:

std::fill(orders, orders + Size, static_cast<LimitOrder*>(0));

But then again, why go through the process in the first place when you can zero-initialize the array in the initializer list?

InternalIdAssigner::InternalIdAssigner()
   : lastCleanId(), orders() {}
like image 61
David Rodríguez - dribeas Avatar answered Oct 26 '25 05:10

David Rodríguez - dribeas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!