I am aware you cannot use an initialiser list for an array. However I have heard of ways that you can set an array of pointers to NULL in a way that is similar to an initialiser list.
I am not certain how this is done. I have heard that a pointer is set to NULL by default, though I do not know if this is guaranteed/ in the C++ standard. I am also not sure if initialising through the new operator compared to normal allocation can make a difference too.
Edit: I mean to do this in a header file/constructor initialisation list. I do not want to put it in the constructor, and I do not want to use a Vector.
We can directly assign the pointer variable to 0 to make it null pointer.
If you have a char[] , you can zero-out individual elements using this: char arr[10] = "foo"; arr[1] = '\0'; Note that this isn't the same as assigning NULL , since arr[1] is a char and not a pointer, you can't assign NULL to it.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With