2013-04-12 53 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