大家好,我有两个结构:一个是 key 对,另一个是节点。
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);
这就够了吗?
谢谢!
最佳答案
VL 数据
的内存是作为node
结构的一部分分配的,不需要重新分配。
尝试:
struct node *temp = malloc(sizeof(node));
temp->left = NULL;
temp->right = NULL;
(temp->data).key = key;
(temp->data).value = &value;
关于c - 在另一个结构中初始化并获取结构变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15963109/