C 无法打印链接列表
我无法打印整个链接列表。。 我犯了什么错?我不熟悉链表 这是基本结构C 无法打印链接列表,c,struct,linked-list,C,Struct,Linked List,我无法打印整个链接列表。。 我犯了什么错?我不熟悉链表 这是基本结构 struct data { int id; int age; struct data *next; }; 主要功能 int main() { int mode; struct data *initial; struct data *insert; struct data *temp; insert = initial; printf("1. Inser
struct data {
int id;
int age;
struct data *next;
};
主要功能
int main() {
int mode;
struct data *initial;
struct data *insert;
struct data *temp;
insert = initial;
printf("1. Insert\n5. Print List\n");
while (1) {
printf("Mode: ");
scanf("%d", &mode);
if (mode == 1) {
insert = malloc(sizeof(struct data));
printf("Id: ");
scanf("%d", &(insert->id));
printf("Age: ");
scanf("%d", &(insert->age));
insert=insert->next;
} else if (mode == 5) {
temp = initial;
while (temp != insert) {
printf("Id: %d\tAge: %d\n", temp->id, temp->age);
temp = temp->next;
}
}
}
}
谢谢您的帮助。您从未将
initial
初始化为任何内容,甚至NULL
或0
,因此您无法明智地从中获取列表
您还需要设置insert->next=NULL代码>在两次scanf()
调用之后和分配之前insert=insert->next代码>。您需要以某种方式将插入到原始列表中;可能使用struct data*initial=0代码>当它被声明时,如果(initial==0)initial=insert,则代码>在insert=insert->next之前代码>
您还需要做更多的错误检查:scanf()
和malloc()
都可能失败,当它们失败时,您应该做一些明智的事情。除了@JonathanLeffler提出的观点外,我还看到了这段代码中的问题:
if(mode==1)
{
insert=malloc(sizeof(struct data));
printf("Id: ");scanf("%d",&(insert->id));
printf("Age: ");scanf("%d",&(insert->age));
insert=insert->next;
}
第一次执行此块时,请执行以下操作:
为结构数据创建内存,并让插入指向它
填写结构数据中的数据
使insert
成为insert->next
。但是insert->next
未初始化为语句之前的任何内容。在语句末尾,insert指向完全不可预测的内容
由于没有指向分配的内存,因此无法跟踪该内存
第二次执行此块时,请执行以下操作:
为结构数据创建内存,并让插入指向它
填写结构数据中的数据
使insert
成为insert->next
。但是insert->next
未初始化为语句之前的任何内容。在语句末尾,insert指向完全不可预测的内容
由于没有指向分配的内存,因此无法跟踪该内存
这里发生了什么事
你重复了同样的过程
您丢失了对malloc
的两次调用所分配的内存
insert
仍然指向一些不可预测的东西
每次执行该循环时,此过程都会重复
这是你能解决的问题
if(mode==1)
{
// Allocate memory and let temp point
// to the allocated memory.
temp=malloc(sizeof(struct data));
// Fill up the data of the newly allocated memory.
printf("Id: ");scanf("%d",&(temp->id));
printf("Age: ");scanf("%d",&(temp->age));
// Make temp clean by making its next point to NULL.
temp->next = NULL;
// Now figure out where to link this newly allocated
// memory to the linked list.
// Assuming you initialize insert correctly...
if ( insert == NULL )
{
initial = insert = temp;
}
else
{
insert->next = temp;
insert = temp;
}
}
希望这是有意义的。好的;因此,您需要进行一些调试。在insert中丢失值之前,还需要将insert->next
设置为新分配的结构。坚持下去;你最终会到达那里的。