【问题标题】:How to initialize an array of pointer inside a struct by using struct constructor?如何使用结构构造函数初始化结构内的指针数组?
【发布时间】:2017-09-14 17:47:40
【问题描述】:

我试过memset喜欢

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

但出现警告

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

还有其他方法可以初始化指向NULL的指针数组吗?

【问题讨论】:

  • TreeNode* branches[3] = {}; 在声明中。
  • NULL不等于0吗?
  • 如果您在源代码中将 NULL 更改为 0,它将正常编译。但只要按照 NathanOliver 的建议去做。

标签: c++ arrays constructor initialization


【解决方案1】:

我们可以在成员初始化列表中初始化数组,而不是使用memset。如果我们使用

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

然后braches 将被零初始化。这是可行的,因为初始化列表中每个缺失的初始化器都会导致相应的元素初始化为零。

【讨论】:

  • 谢谢!但是如何用 nullptr 初始化分支呢?它与 0 不同。
  • @danche 0 是空指针。 nullptr 只是 0 转换为指针类型。
  • 所以我们不需要branches{nullptr, nullptr, nullptr}?
  • @danche 你可以,但你不需要它。 braches{} 会做你想做的事。
  • braches{} 本质上是braches{0, 0, 0} 本质上是branches{nullptr, nullptr, nullptr}
猜你喜欢
  • 2012-02-08
  • 2020-08-06
  • 1970-01-01
  • 2015-08-08
  • 1970-01-01
  • 1970-01-01
  • 2020-03-12
  • 2010-09-16
  • 1970-01-01
相关资源
最近更新 更多