【问题标题】:nested struct with nested pointers带有嵌套指针的嵌套结构
【发布时间】: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 -&gt; head 仍然指向NULL
  • 一旦你写了ptr = malloc...,那么ptr就不再是t-&gt;head。而且您从未将 t-&gt;head 设置为除 NULL 之外的任何内容,因此它仍然为 NULL。
  • 不要不要 typedef指针!

标签: c pointers struct pointer-to-pointer


【解决方案1】:

您必须将ptr 分配回t-&gt;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-&gt;head 仅将t-&gt;head 的值分配给ptrptr = malloc(....) 分配动态内存并将内存地址分配给ptr 并覆盖之前存在的t-&gt;head 的值。但是内存的地址永远不会分配给t-&gt;headptrt-&gt;head 之间没有神奇的联系。

你试图做的事情是这样的:

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

在这种情况下,ptr 是指向t-&gt;head 的指针,*ptr = malloc( sizeof(struct node) ) 分配了ptr 所指的已分配内存的地址,即t-&gt;head

【讨论】:

  • 这里的事情有点棘手。给出了所有的定义代码,我对此无能为力。我要实现的是一个包含完整有序树的表,其中存储了树的头部。如果您将 ptr 实现为指向 t->head 的指针,那么,如果我想使用 ptr 遍历树怎么办(比如插入一个新节点,我需要遍历树并对tree) , t->head 也会被改变,然后我会失去 head。
  • 我知道为什么这不起作用,但我不知道如何解决它。我在下面提出了进一步的问题,希望你能帮助我。谢谢。stackoverflow.com/questions/35384096/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-09-23
  • 1970-01-01
  • 2021-02-13
  • 2010-11-14
  • 1970-01-01
  • 2019-05-25
  • 1970-01-01
相关资源
最近更新 更多