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