Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

When I try to malloc() a struct bstree node, my compiler is reporting an error:

invalid conversion from 'void*' to 'bstree*'

Here is my code:

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;
}
like image 912
user3697329 Avatar asked Dec 14 '22 07:12

user3697329


1 Answers

In C++ there is no implicit conversion from type void * to pointer of other type. You have to specify explicit casting. For example

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

or

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

Also in C++ you should use operator new instead of the C function malloc.

like image 103
Vlad from Moscow Avatar answered Dec 24 '22 02:12

Vlad from Moscow