c - 我的链接列表中的分配不起作用

标签 c list insert singly-linked-list

我正在尝试实现一个链接列表,仅当列表中尚不存在时才插入该项目。如果该项目存在,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 说它尚未初始化

最佳答案

正如风向标指出的那样,

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 的结果。malloc 返回的指向 void 的指针与任何指针兼容。)

关于c - 我的链接列表中的分配不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57290522/

相关文章:

c - 打开文件给出意外的返回值

c - g_main_loop 在 gtk 编程中如何工作?

python - 将嵌套列表中的特定组件从字符串更改为浮点

php - 在mysql数据库中动态插入非英语(印地语)

php - 关于DomDocument效率的问题

c - 未排序日志文件中最快的搜索。有没有比线性搜索更有效的方法?

python - 删除点列表中相似点的最佳方法

python - 处理列表和一个非列表类型的元素

c# - string.insert 多个值。这可能吗?

c - 是否有任何 C 编译器会警告使用未声明的定义