【发布时间】:2023-03-10 05:23:01
【问题描述】:
我正在使用数据结构来实现拼写检查。我有两个结构,节点和表,定义如下:
#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 的变化而变化??
【问题讨论】:
-
ptr = malloc(sizeof(tree_ptr));-->>ptr = malloc(sizeof *ptr);哦,typedefs的快乐...快乐快乐快乐快乐快乐... -
@wildplasser 抱歉,它仍然无法工作。
-
"那么当我改变ptr的值时,为什么t->head没有以同样的方式改变?" -- 因为
ptr是指向malloced 内存段和t -> head仍然指向NULL。 -
一旦你写了
ptr = malloc...,那么ptr就不再是t->head。而且您从未将t->head设置为除 NULL 之外的任何内容,因此它仍然为 NULL。 -
不要不要
typedef指针!
标签: c pointers struct pointer-to-pointer