我正在使用数据结构来实现拼写检查。我有两个结构,节点和表,定义如下:
#include <stdlib.h>
typedef struct node *tree_ptr;
typedef struct table * Table;
struct node
{
char* element;
tree_ptr left, right;
};
typedef struct table
{
tree_ptr head;
int tree_h;
}table;
int main() {
Table t = malloc(sizeof(table));
t->head = NULL;
tree_ptr ptr = t->head;
ptr = malloc(sizeof(tree_ptr));
ptr->element = "one";
ptr->left = NULL;
ptr->right = NULL;
printf("%s\n",t->head->element);
return 0;
}
这个程序在 print 函数的最后一行有 bug,因为 t->head 指向 NULL。
据我所知,当更改指针的内容值时,指针指向的变量会自动更改。
由于 t->head 和 ptr 都是指针,而 ptr 指向 t->head,也就是说,它们指向的是同一个对象。
那么当我改变ptr的值时,为什么t->head不会以同样的方式改变?我应该怎么做才能实现 t->head 随着 ptr 的变化而变化?