【问题标题】:C++ malloc invalid conversion from `void*' to structC++ malloc 从 `void*' 到 struct 的无效转换
【发布时间】:2023-03-16 08:15:02
【问题描述】:

当我尝试malloc() struct bstree 节点时,我的编译器报告错误:

从“void*”到“bstree*”的无效转换

这是我的代码:

struct bstree {
    int key;
    char *value;

    struct bstree *left;
    struct bstree *right;
};

struct bstree *bstree_create(int key, char *value) {
    struct bstree *node;

    node = malloc(sizeof (*node));

    if (node != NULL) {
        node->key = key;
        node->value = value;
        node->left = NULL;
        node->right = NULL;
    }
    return node;
}

【问题讨论】:

  • 您是否尝试使用 C++ 编译器编译 C 代码?

标签: c++ c pointers dynamic-memory-allocation


【解决方案1】:

在 C++ 中,没有从类型 void * 到其他类型指针的隐式转换。您必须指定显式转换。例如

node = ( struct bstree * )malloc(sizeof (*node));

node = static_cast<struct bstree *>( malloc(sizeof (*node)) );

同样在 C++ 中,您应该使用运算符 new 而不是 C 函数 malloc

【讨论】:

  • 在 C++ OP 中不应在给定上下文中使用 struct
  • @SergeyA 为什么不使用详细的名称?我看不出有什么原因。
  • @SergeyA 我不明白你在说什么。我没有看到任何“噪音”。我看到了一份自我说明。
  • 没有自文档。 (struct bstree*) 从编译器的角度来看与 (bstree*) 是一样的,并且不会向人类读者添加任何信息,但它长了 7 个字符。因此它是语法噪音。
  • @SergeyA 该项目可以包含 C 和 C++ 模块。结构的声明可以具有 C 链接语言并放置在 C 标头中。 bstree 可以是 typedef,也可以是聚合的非聚合类 insetad 等等。
【解决方案2】:

在 C 中,您的代码“很好”。

在 C++ 中,你想定义一个构造函数:

struct bstree {
    int key;
    char *value;

    bstree *left;
    bstree *right;

    bstree (int k, char *v)
        : key(k), value(v), left(NULL), right(NULL)
    {}
};

然后使用new,例如:node = new bstree(key, value);

【讨论】:

  • 在 C++ 中你不想要struct bstree* left
  • 没有错,但在这种情况下是多余的。
【解决方案3】:

演员可以修复这个错误:

node = (struct bstree *) malloc(sizeof (*node));

我展示了一个 C 风格的转换,因为代码看起来是 C。还有一个 C++ 风格的转换:

node = static_cast<struct bstree *>(malloc(sizeof (*node)));

【讨论】:

  • 为什么在 C++ 的强制转换上下文中使用 struct
  • @SergeyA:在 C 中,结构类型名称必须在声明和类型转换中以 struct 关键字为前缀。 struct 关键字在 C++ 中是可选的。
  • @RemyLebeau,是的,我知道这一点。但是,我们(有点)建立的 OP 在这里使用 C++。那么这里有什么意义呢?
  • 在 C++ 中根本不应该有演员表
猜你喜欢
  • 2017-02-17
  • 2019-03-15
  • 2011-07-03
  • 2016-03-21
  • 2017-06-30
  • 1970-01-01
  • 2013-08-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多