2013-04-12 52 views
0

嘿傢伙我有兩個結構:一個是密鑰對,另一個是節點。在另一個結構中初始化並獲取結構變量?

typedef struct { 
    char *key; 
    void *value; 
} VL; 

typedef struct node{ 
    struct node *left; 
    struct node *right; 
    VL data; 
} BST; 

我該如何去初始化節點struct並在裏面添加VL struct? 這是我到目前爲止有:

// Create new node 
    struct node *temp = malloc(sizeof(node)); 
    temp->left = NULL; 
    temp->right = NULL; 

    struct VL *vl = malloc(sizeof(VL)); 
    vl->key = key; 
    vl->value = &value; 

    temp->data= *vl; 

而且我也試過,如設置TEMP-> data.key加鍵等等,所有這些都返回錯誤很多其他的事情。所以我來這裏尋求幫助:)。

另外我該如何去從節點獲取數據?

char *key = (char *)5; 
void *val = "hello"; 
// create node with this key/val pair and insert into the tree, then print 
printf("key = %d; value = %s\n", (int)head->data.key, (char*)head->data.value); 

這樣就夠了嗎?

謝謝!

+0

爲什麼你想輸出'key'爲您的最終'printf'整數?什麼是期望的輸出?這個陳述很難閱讀,有些令人困惑。 – hoxworth

回答

3

VL data的內存被分配爲node結構的一部分,不需要重新分配。

嘗試:

struct node *temp = malloc(sizeof(node)); 
temp->left = NULL; 
temp->right = NULL; 
(temp->data).key = key; 
(temp->data).value = &value; 
+0

謝謝,這工作! – Travv92