Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 764
user233320 Avatar asked Apr 10 '10 21:04

user233320


People also ask

Can you set pointers to null?

We can directly assign the pointer variable to 0 to make it null pointer.

Can you set an array element to null in C?

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.


2 Answers

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.

like image 142
AnT Avatar answered Oct 22 '22 01:10

AnT


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 
like image 22
Paul R Avatar answered Oct 21 '22 23:10

Paul R