首页 > 解决方案 > 我的链接列表中的作业不起作用

问题描述

我正在尝试实现一个链接列表,该列表仅在列表中不存在时才插入项目。如果该项目存在,则ent_exists返回指向该项目的指针。

typedef struct nodo_ent{
  struct nodo_ent *next;
  char *ent;
}nodo_ent;

nodo_ent *head;
nodo_ent *tail;
head = NULL;
tail = NULL;

nodo_ent *ent_exists(char *ent)
{
  if (head == NULL)
 {
   return NULL;
 }
 else
 {
   nodo_ent *cursor;
   cursor = head;
   while (cursor != tail)
   {
     if (strcmp(cursor->ent, ent) == 0);
     {
       return cursor;
     }
     cursor = cursor->next;
   }
   if (strcmp(tail->ent, ent) == 0);
   {
     return tail;
   }
   return NULL;
 }
}

void addent(char *ent)
{
  if (ent_exists(ent) != NULL)
  {
    return;
  }
  else
  {
    nodo_ent nodo = {NULL, ent};
    nodo_ent *ptr;
    ptr = (nodo_ent*)malloc(sizeof(nodo_ent));
    ptr = &nodo;
    if (head == NULL)
    {
      head = ptr;
      tail = ptr;
    }
    else
    {
      tail->next = ptr;
      tail = ptr;
    }
    return;
  }
}


在第一次调用“addent”之后,“head”和“tail”都指向添加节点的地址,但是当我第二次调用它并尝试访问 tail->ent(在 ent_exists 中)时,valgrind 说它是未初始化

标签: clistinsertsingly-linked-list

解决方案


正如风向标所指出的,

nodo_ent nodo = {NULL, ent};
nodo_ent *ptr;
ptr = (nodo_ent*)malloc(sizeof(nodo_ent));
ptr = &nodo;

此序列分配内存,然后用局部变量的地址覆盖指向此分配内存的指针nodo

然后你处理这个局部变量,但是当函数返回时,那个局部变量不再存在并且你的列表被破坏了。

您拥有一切,只需使用:

nodo_ent *ptr;
ptr = malloc(sizeof(nodo_ent));

(并且不要转换 malloc 的结果void。malloc 返回的指向 的指针与任何指针兼容。)


推荐阅读