0

I have a simple C++ Node class which contains an array data member of pointers to the same type. This array is dynamically allocated and its pointers should default to null but I'm not sure how to achieve it.

class Node
{
private:
    Node *_nextNode[];
    string _data;
}

Node::Node( const string &p_data, const int &p_levels ): _data(p_data)
{
   //unsure how to initialize the '_nextNode[]' member so that the size of the array is of p_levels and they all default to null pointers 
}

class SkipList
{
    private:

}
trincot
  • 317,000
  • 35
  • 244
  • 286
user2211776
  • 239
  • 1
  • 2
  • 11

3 Answers3

2

Use a std::vector<Node*>:

Node::Node( const string &p_data, const int &p_levels ): 
    _data(p_data),
    _nextNode(p_levels)
{

this will initialise the elements of _nextNode to nullptrs.

Consider using a smart pointer implementation instead of Node* to manage the destruction of the Node instances for you.


If you have to use a Node* then you need a Node** to point to a list of Node*:

class Node
{
private:
    Node**_nextNode;
    string _data;
};

Node::Node( const string &p_data, const int &p_levels ): 
    _data(p_data),
    _nextNode(new Node*[p_levels]())
{                              //^^ value initialization.

allocates an array of int* containing p_levels elements and value initializes them (sets them to NULL). Node needs to know how many elements are stored in _nextNode so p_levels would require storing also. Destruction:

for (int i = 0; i < _nextNodeElements; i++)
{
    delete _nextNode[i]; // delete NULL is safe, a no-op.
}
delete[] _nextNode;

Just to push you toward std::vector again: std::vector<std::unique_ptr<Node>> _nextNode; wouldn't require a hand-written destructor, the default generated one would suffice.

Community
  • 1
  • 1
hmjd
  • 120,187
  • 20
  • 207
  • 252
1
_nextNode = new Node[pLevels];
memset ( _nextNode, 0, sizeof (_nextNode));

Is this what you want? Also you should declare Node *_nextNode[] as Node *_nextNode And you will also have to include <string.h> for memset

Bill
  • 5,263
  • 6
  • 35
  • 50
0

Try using Node **_nextNode istead of Node *_nextNode[].

Node **_nextNode= new (NODE**)[ArraySize];
for (int i = 0; i < rows; ++i) {
 _nextNode = NULL;

}

titan
  • 664
  • 6
  • 18