我有以下代码片段:
struct TreeNode *allocate_node(char *value) {
struct TreeNode *new_node = malloc(sizeof(struct TreeNode));
new_node->value = value;
new_node->sibling = NULL;
new_node->child = NULL;
return new_node;
}
void tree_insert(struct TreeNode *root, char **values) {
struct TreeNode *prev = root;
struct TreeNode *curr = prev->child;
for (int i = 0; i < 4; i++) {
if (!curr) {
prev->child = allocate_node(values[i]);
prev = prev->child;
curr = prev->child;
}
}
}
int main(void) {
struct TreeNode root;
root.value = "";
root.child = NULL;
root.sibling = NULL;
char *command1[] = {"a", "b", "c", "d"};
char *command2[] = {"e", "f", "g", "h"};
tree_insert(&root, command1);
tree_insert(&root, command2);
printf("Printing current tree values: \n");
struct TreeNode *curr = root.child;
while (curr) {
printf("%s ", curr->value);
curr = curr->child;
}
}
预期输出:
Current tree values:
a b c d
实际输出:
Current tree values:
e f g h
运行第一个tree_insert后,我的树被链接成这样:(根)-> a-> b-> c-> d
但是当第二个tree_insert运行时,即使tree_insert甚至不应该运行,我的老树似乎也已被替换。新树是这样的:(根)-> e-> f-> g-> h
由于在第二个tree_insert中,curr不再为NULL,它为什么仍在运行并覆盖我的树?我是C语言的新手,所以我可能会缺少一些明显的东西
编辑:TreeNode的定义如下:
struct TreeNode {
char *value;
struct TreeNode *sibling;
struct TreeNode *child;
};
new_node->value = value;
此行使我相信您将指针value
存储在结构中。
这里的问题是指针存储在结构中。该指针指向其他位置,通常在堆栈中。更改此变量后,结构中的数据也会更改。
您可以将数据以数组的形式存储在结构中,也可以使用动态内存分配来存储数据。
对于动态内存分配,功能allocate_node
如下更改。
struct TreeNode *allocate_node(char *value) {
struct TreeNode *new_node = malloc(sizeof(struct TreeNode));
int len = strlen(value);
new_node->value = malloc(len +1);
strcpy(new_node->value, value);
new_node->sibling = NULL;
new_node->child = NULL;
return new_node;
}
要存储在数组中,您需要事先知道value
的最大长度。在这种情况下,需要进行以下更改。
struct TreeNode {
char value[MAXLEN + 1];
struct TreeNode *sibling;
struct TreeNode *child;
};
struct TreeNode *allocate_node(char *value) {
struct TreeNode *new_node = malloc(sizeof(struct TreeNode));
strcpy(new_node->value,value);
new_node->sibling = NULL;
new_node->child = NULL;
return new_node;
}