0

我正在使用数据结构来实现拼写检查。我有两个结构,节点和表,定义如下:

#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 的变化而变化?

4

1 回答 1

2

您必须分配ptrt->head. 除此之外,您必须sizeof(struct node)为一个节点分配:

int main() {
    Table t = malloc(sizeof(table));
    t->head = NULL;

    tree_ptr ptr = malloc( sizeof(struct node) );
                              //         ^^^^      
    ptr->element = "one";
    ptr->left = NULL;
    ptr->right = NULL;

    t->head = ptr; // <-------

    printf("%s\n",t->head->element);
   return 0;
} 

注意ptr = t->head只分配t->headto的值ptrptr = malloc(....)分配动态内存并将内存地址分配给ptr并覆盖t->head之前的值。但是内存的地址永远不会分配给t->head. ptr和之间没有神奇的联系t->head

你试图做的是这样的:

tree_ptr *ptr = &(t->head);
*ptr = malloc( sizeof(struct node) );
(*ptr)->element = "one";
(*ptr)->left = NULL;
(*ptr)->right = NULL

在这种情况下ptr,是一个指针,t->head*ptr = malloc( sizeof(struct node) )分配了所分配内存的地址,其中ptr指的是 ,即t->head

于 2016-02-13T15:48:38.807 回答