C++ How do you set an array of pointers to null in an initialiser list like way?

You can switch from array to std::vector and use

std::vector<T*> v(SIZE);

The values will be initialized by NULLs automatically. This is the preferred C++ way.


Update: Since C++11, there is one more way: using

std::array<T*, SIZE> array = {};

This behaves more like a corrected version of C-style array (in particular, avoids dynamic allocations), carries its size around and doesn't decay to a pointer. The size, however, needs to be known at compile time.


In order to set an array of pointers to nulls in constructor initializer list, you can use the () initializer

struct S {
  int *a[100];

  S() : a() {
    // `a` contains null pointers 
  }
};

Unfortunately, in the current version of the language the () initializer is the only initializer that you can use with an array member in the constructor initializer list. But apparently this is what you need in your case.

The () has the same effect on arrays allocated with new[]

int **a = new int*[100]();
// `a[i]` contains null pointers 

In other contexts you can use the {} aggregate initializer to achieve the same effect

int *a[100] = {};
// `a` contains null pointers 

Note that there's absolutely no need to squeeze a 0 or a NULL between the {}. The empty pair of {} will do just fine.


Normally an array will not be initialised by default, but if you initialise one or more elements explicitly then any remaining elements will be automatically initialised to 0. Since 0 and NULL are equivalent you can therefore initialise an array of pointers to NULL like this:

float * foo[42] = { NULL }; // init array of pointers to NULL