具有嵌套指针的嵌套结构

nested struct with nested pointers

我正在使用数据结构来执行拼写检查。我有两个结构,node 和 table,定义如下:

#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;
} 

这个程序在打印函数的最后一行有错误,因为 t->head 指向 NULL。

据我所知,当改变指针的内容值时,指针指向的变量会自动改变。

由于t->head和ptr都是指针,ptr指向t->head,也就是说,它们指向的是同一个对象。

那当我改变ptr的值时,为什么t->head没有以同样的方式改变??我应该怎么做才能实现 t->head 随着 ptr 的变化而变化??

您必须将 ptr 分配回 t->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->head的值赋给了ptrptr = malloc(....) 分配动态内存并将内存地址分配给 ptr 并覆盖之前存在的 t->head 的值。但是内存的地址从来没有分配给t->headptrt->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.