C++ malloc无效从`void*'转换为struct

use*_*329 3 c c++ pointers dynamic-memory-allocation

当我尝试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;
}
Run Code Online (Sandbox Code Playgroud)

Vla*_*cow 8

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

node = ( struct bstree * )malloc(sizeof (*node));
Run Code Online (Sandbox Code Playgroud)

要么

node = static_cast<struct bstree *>( malloc(sizeof (*node)) );
Run Code Online (Sandbox Code Playgroud)

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