【问题标题】:Initialize and get struct variables in another struct?在另一个结构中初始化并获取结构变量?
【发布时间】:2013-04-12 04:33:02
【问题描述】:

大家好,我有两个结构:一个是密钥对,另一个是节点。

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

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

我将如何初始化节点结构并在其中添加 VL 结构? 这是我目前所拥有的:

    // 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 设置为 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);

够了吗?

谢谢!

【问题讨论】:

  • 您为什么要在最终的printf 中将key 输出为整数?期望的输出是什么?该声明难以阅读,而且有些令人困惑。

标签: c linux struct tree binary-search-tree


【解决方案1】:

VL data 的内存是作为node 结构的一部分分配的,不需要重新分配。

试试:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-20
    相关资源
    最近更新 更多