2016-04-05 102 views
3

當我嘗試malloc()一個struct bstree節點,我的編譯器報告錯誤:C++的malloc無效轉換到結構

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; 
} 
+8

你想用C++編譯器編譯C代碼嗎? – SergeyA

回答

8

在C++中沒有來自void *類型其它類型的指針的隱式轉換。你必須指定明確的轉換。例如

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

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

此外,在C++中,你應該使用操作new不是C函數malloc的。

+0

在C++中,OP不應該在給定的上下文中使用'struct'。 – SergeyA

+0

@SergeyA爲什麼不使用詳細名稱?我沒有看到任何理由。 –

+0

降低代碼的信噪比。 – SergeyA

0

一演員將修復此錯誤:

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

我已經顯示了C風格的轉換,因爲代碼似乎是C.還有一個C++ - 樣式轉換:

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

爲什麼在C++的投射環境中使用'struct'? – SergeyA

+0

@SergeyA:在C中,結構類型名稱必須在聲明和類型轉換中以'struct'關鍵字作爲前綴。在C++中'struct'關鍵字是可選的。 –

+0

@RemyLebeau,是的,我知道這一點。但是,我們(有點)建立OP是在這裏使用C++。那麼這裏有什麼意義呢? – SergeyA

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

+0

在C++中,您不需要'struct bstree * left'。 – SergeyA

+1

它沒有問題,但在這方面它是多餘的。 – jxh