C++ malloc 从“void*”到 struct 的无效转换

C++ malloc invalid conversion from `void*' to struct

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

invalid conversion from 'void*' to '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;
}

转换将修复此错误:

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

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

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

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

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

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

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

在 C 中,您的代码是 "fine"。

在 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);.