我正在制作一个简单的数据库程序来学习结构和二叉树。我创建了一个包含 3 个字段的全局结构 Student
:名字、姓氏、年龄,并编写了一个函数来获取 3 个用户输入(存储为字符串 in_fname
、in_sname
和 int in_age
,比方说)并将它们放入临时结构 new
中,并计划将它们复制到主树的适当位置.在获取第一个条目的用户输入后,我有:
struct Student *new;
new = (Student *) malloc (sizeof(struct Student));
strcpy (new->fname, in_fname);
strcpy (new->sname, in_sname);
new->age = in_age;
new->left = new->right = NULL;
printf("Contents of new is '%s', '%s', '%d'.\n",new->fname, new->sname, new->age);
student_tree = new /* wanting to copy the new student as the first entry in the tree*/
现在当我
print("Contents of structure is '%s', '%s', '%d'.\n",student_tree->fname, student_tree->sname, student_tree->age);
我得到了正确的条目,表明复制成功了,但是当我
free(new)
print("Contents of structure is '%s', '%s', '%d'.\n",student_tree->fname, student_tree->sname, student_tree->age);
(认为它是临时的,我不再需要它了)当我第一个条目 fname
总是损坏,包含垃圾。
有人可以解释我错过了什么吗?不一定要固定的代码,只是想了解为什么当我从中复制的东西消失时树中结构的内容会发生变化,以及如何永久复制它。
非常感谢,
W
最佳答案
因为student_tree
和new
是指针。当你将new
赋值给student_tree
时,没有复制,它只是让student_tree
指向同一个内存。当你调用free(new)
时,它会回收new
指向的内存,也就是student_tree
指向的内存,所以可以理解垃圾。
下面是一些将执行实际复制的代码:
struct Student* student_tree = malloc(sizeof(struct Student));
*student_tree = *new;
这里我创建了指针student_tree
,分配内存来存放struct Student
,最后将new
指向的内存中的内容放入code>在student_tree
指向的内存中。
关于复制结构的内容在临时结构为 `free` d 后发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50090878/