Amir Havangi
Amir Havangi

Reputation: 45

Defining NULL for an array of pointers in C++

I wrote a class in C++. In it I wrote:

class Node{
private:
Node*m[200]=NULL;
};

(This is a part of the class) But I receive errors. What should I do for defining an array of pointers, NULL ?

Upvotes: 0

Views: 1001

Answers (3)

Emil Laine
Emil Laine

Reputation: 42828

Since you're writing C++, I'd recommend avoiding raw arrays and using std::vector instead (or std::array if you have C++11).

In pre-C++11 you need initialize your members in the constructor:

class Node
{
public:
    Node() : m(200) {}

private:
    std::vector<Node*> m;
};

This will initialize m to hold 200 null pointers when you construct a Node.

Upvotes: 1

juanchopanza
juanchopanza

Reputation: 227390

For completeness, if you don't have C++11 support, you can value initialize the array in a constructor. This has the effect of zero initializing the elements:

class Node
{
public:
  Node() : m() {}
private:
  Node* m[200];
};

Note also that value initializing instances of the original Node has the same effect WRT zero initializing the elements:

Node n = {}; // Node must be aggregate, as in original code.

Upvotes: 2

M.M
M.M

Reputation: 141554

To make all 200 pointers be null, write:

class Node
{
    Node *m[200] = {};
};

This is only valid in C++11 and later.

Upvotes: 6

Related Questions