c - 我的链接列表中的作业不起作用
问题描述
我正在尝试实现一个链接列表,该列表仅在列表中不存在时才插入项目。如果该项目存在,则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 的结果void
。malloc 返回的指向 的指针与任何指针兼容。)
推荐阅读
- prolog - prolog clp 标签 - 忽略一些变量?
- javascript - 图表不显示在 Django 应用程序的网页上(使用 Chart.js)
- javascript - Node js表单提交导致以下错误 - 错误:无法POST /
- sql - SQL-在每个用户第 n 次发生事件后返回行
- php - 我可以在wordpress的这个区域添加一个按钮吗?
- google-apps-script - 如何使用辅助表存储电子邮件,根据任务状态向特定人员发送自动电子邮件?
- swift - 在 Swift 中从 UIView 创建 PDF
- pandas - pyspark 中的 defaultdict 实现
- javascript - 通过Id nodejs获取多个元素
- sql - 我有这个错误 ORA-00917:缺少逗号?