Initialize a pointer to a class with NULL values

arrays, c++, pointers

Solution

First of all, the simplest solution is to do the following:

Node** buckets = new Node*[SIZE]();

As litb previously stated, this will value initialize `SIZE` pointers to null pointers.

However, if you want to do something like `Node **buckets` and initialize all of the pointers to a particular value, then I recommend `std::fill_n` from `<algorithm>`

Node **buckets = new Node*[SIZE];
std::fill_n(buckets, SIZE, p);

this will set each `Node*`' to `p` after allocation.

In addition, if you want the Node to have sane member valuesupon construction, the proper way is to have a constructor. Something like this:

struct Node {
    Node() : data(0), next(NULL){}
    Node(int d, Node *n = NULL) : data(d), next(n) {}

    int data;
    Node* next;
};

That way you can do this:

Node *p = new Node();

and it will be properly initialized with 0 and NULL, or

Node *p = new Node(10, other_node);

Finally, doing this:

Node *buckets = new Node[N]();

will construct `N` `Node` objects and default construct them.

Problem

I am tring to intialize an array of pointers to a NODE struct that I made ``` struct Node{ int data; Node* next; }; the private member of my other class is declared as Node** buckets; ``` It is currently initialised as buckets = new Node*[SIZE] Is there anyway to initialize the array so that its members point to NULL or some other predefined Node pointer? EDIT: Im looking for a means to initilize it without trying to generate a for loop to traverse through the full lenght of the array. The size of the array is determined at runtime. EDIT 2: I tried std::fill_n(buckets, SIZE_OF_BUCKET, NULL); but the compiler gives the error "cannot convert from 'const int' to 'Node *'" I am using visual studio 2008. Is there something wrong that I am doing?

Original source

Related problems