1

I tried memset like

struct TreeNode {
    bool exist;
    bool word_ending;
    TreeNode* branches[3];
    TreeNode(): exist(true), word_ending(false) {
        memset(branches, NULL, sizeof(branches));
    }
};

but there appears warnings

warning: implicit conversion of NULL constant to 'int' [-Wnull-conversion]
        memset(branches, NULL, sizeof(branches));
        ~~~~~~           ^~~~
                         0
1 warning generated.

Is there some other way to initialize the array of pointer to NULL?

3
  • TreeNode* branches[3] = {}; in the declaration. Commented Sep 14, 2017 at 17:50
  • Isn't NULL equivalent to 0? Commented Sep 14, 2017 at 17:50
  • 1
    If you change NULL to 0 in the source it will compile fine. But just do what NathanOliver suggested. Commented Sep 14, 2017 at 17:56

1 Answer 1

4

Instead of using memset we can initialize the array in the member initialization list. If we use

TreeNode(): exist{true}, word_ending{false}, braches{} {}

Then braches will be zero initialized. This works because each missing initializer in a initialization list causes the corresponding element to zero initialized.

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

6 Comments

Thanks! But how to initialize branches with nullptr? It is not same as 0.
@danche 0 is the null pointer. nullptr is just 0 casted to the pointer type.
so we don't need branches{nullptr, nullptr, nullptr}?
@danche You can but you don't need it. braches{} will do exactly what you want.
braches{} is essentially braches{0, 0, 0} which is essentially branches{nullptr, nullptr, nullptr}
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.