提问人:khoprutu 提问时间:12/15/2021 最后编辑:khoprutu 更新时间:12/15/2021 访问量:49
当我使用双向链表中的最后一个指针时,代码崩溃
code crashes when i use the last pointer in doubly linked list
问:
所以我为一个双向链接列表写了一些代码,在制作一个在末尾添加节点的函数时,我想为最后一个节点制作一个指针,但是当我执行它进行添加时,它崩溃了,但在前端添加它工作正常。一切看起来都很好,它甚至没有显示任何错误,只是崩溃。
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *lptr;
struct node *rptr;
};
typedef struct node *Node;
Node pos(Node first, Node last)
{
Node new;
new = (Node)malloc(sizeof(struct node));
new->lptr = NULL;
new->rptr = NULL;
printf("Enter data: ");
scanf("%d", &new->data);
if (first == NULL)
{
first = new;
last = new;
}
else
{
int p;
printf("1) First\n2) Last\n");
scanf("%d", &p);
switch (p)
{
case 1:
first->lptr = new;
new->rptr = first;
first = new;
break;
case 2:
last->rptr = new;
new->lptr = last;
last = new;
break;
default:
break;
}
}
return first;
}
void dis(Node first)
{
Node p;
int c = 1;
if (first == NULL)
{
printf("Empty");
}
else
{ p=first;
while (p != NULL)
{
printf("%dst element is %d\n", c, p->data);
c++;
p = p->rptr;
}
}
}
int main()
{
int ch;
Node first, last, t;
first = NULL;
last = NULL;
for (;;)
{
printf("Insert: \n");
scanf("%d", &ch);
switch (ch)
{
case 1:
first = pos(first, last);
break;
case 2:
dis(first);
break;
default:
printf("invalid");
exit(0);
}
}
return 0;
}
认为问题出在这部分;
case 2:
last->rptr = new;
new->lptr = last;
last = new;
break;
答:
0赞
Vlad from Moscow
12/15/2021
#1
问题在于该函数不会更改 中声明的指针。它更改其局部变量(参数),该变量由指针在 中声明的值 pf 的副本初始化。但是在main中声明的指针保持不变。pos
last
main
last
last
main
last
您应该再声明一个结构,例如
struct List
{
struct node *first;
struct node *last;
};
并将此结构用作函数的参数。
//...
int pos( struct List *list );
int main( void )
{
struct List list = { .first = NULL, .last = NULL };
pos( &list );
//...
}
此外,将函数拆分为两个函数要好得多。第一个会将数据添加到列表的开头,第二个会将数据添加到列表的尾部。
例如
int push_front( struct List *list, int data );
int push_back( struct List *list, int data );
下一个:值未初始化为 c 中的变量
评论
dis
p
else
p
show any error but just crashes.
您是否尝试过 Valgrind 或使用 GDB 逐步检查?first
last
pos
first
last