【发布时间】:2014-08-18 19:29:14
【问题描述】:
我想查看一个链表的所有项目。
我创建了一个三项列表,当我使用下面的“show_items”函数时,它只显示第一个元素,其他项目无法显示,因为编译器给出了分段错误错误。
#include <stdio.h>
#include <stdlib.h>
struct list{
int age;
struct list *next;
};
void create_item(int *total_items, struct list *where_is_first_item, struct list *where_is_last_item)
{
struct list *generic_item;
generic_item = malloc(sizeof(struct list));
printf("\nage of item %d: ", (*total_items)+1);
scanf("%d", &generic_item->age);
if(*total_items == 0){
where_is_first_item->next=generic_item;
where_is_last_item->next=generic_item;
printf("\nitem created\n");
}
else{
where_is_last_item->next=generic_item;
printf("\nitem created\n");
}
void show_items(int *total_items, struct list *where_is_first_item, struct list *temp){
temp=where_is_first_item->next;
int i;
for(i=0;i<*total_items;i++){
printf("age of element %d: %d\n", i+1, temp->age);
temp=temp->next;
}
}
int main (void){
int total_items=0;
struct list *where_is_first_item;
where_is_first_item=malloc(sizeof(struct list));
struct list *temp;
temp=malloc(sizeof(struct list));
printf("\n\n\tCREATE A NEW ITEM\n");
create_item(&total_items, where_is_first_item, where_is_last_item);
total_items++;
show_items(&total_items, where_is_first_item, temp);
return 0;
}
【问题讨论】:
-
你似乎没有初始化你的值。
-
你还没有初始化
generic_item->next。
标签: c list linked-list