Initialize a pointer to a class with null values
I am trying to initialize an array of pointers to a NODE structure that I have created
struct Node{
int data;
Node* next;
};
the private member of my other class is declared as
Node** buckets;
It is currently initialized as buckets = new Node * [SIZE]
Do I need to initialize the array so that its members point to NULL or some other predefined NODE pointer?
EDIT: I'm looking for a facility to initialize without trying to create a for loop to go through the entire length of the array. The size of the array is determined at run time.
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?
source to share
First of all, the simplest solution is to do the following:
Node** buckets = new Node*[SIZE]();
As litb earlier , this would mean initializing pointers SIZE
to null pointers.
However, if you want to do something like Node **buckets
and initialize all pointers to a specific value, I recommend from std::fill_n
<algorithm>
Node **buckets = new Node*[SIZE];
std::fill_n(buckets, SIZE, p);
after highlighting, every Node*
'before will be set p
.
Also, if you want Node to have the correct construct for element values, the correct way is to have a constructor. Something like that:
struct Node {
Node() : data(0), next(NULL){}
Node(int d, Node *n = NULL) : data(d), next(n) {}
int data;
Node* next;
};
This way you can do it:
Node *p = new Node();
and it will be properly initialized with 0 and NULL, or
Node *p = new Node(10, other_node);
Finally, by doing this:
Node *buckets = new Node[N]();
will build the objects N
Node
and build them by default.
source to share