0

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 ?

2
  • 1
    NULL is for pointers, not arrays. It makes no sense to initialize an array with NULL. Commented Mar 17, 2015 at 3:54
  • 2
    Try Node* m[200]{};. But even better, use std::vector instead. Commented Mar 17, 2015 at 3:56

3 Answers 3

6

To make all 200 pointers be null, write:

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

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

Sign up to request clarification or add additional context in comments.

13 Comments

Not sure if this was possible prior to C++11
2.cpp:6:14: warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11 [enabled by default] Node*m[200]={}; ^ 2.cpp:6:14: warning: extended initializer lists only available with -std=c++11 or -std=gnu++11 [enabled by default]
@AmirHavangi do as the error message says, and use -std=c++11 or -std=gnu++11
{ 0 } for pre-C++11.
@Pradhan I'm pretty sure that all inline braced-initializers are invalid before C++11 (your clang may be implementing an extension); what I meant was that I can't think of an alternative means of achieving the same initialization
|
2

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.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.