我有一个写作先到先服务和循环罗宾模拟的作业并比较它们。我开始创建一个用于制作事件列表的链表。我已经制作了insert和print_list函数,但是无法使它工作。我的朋友告诉我使用Doubly Linked List,所以我重新处理了链表,并尝试使插入功能正常工作。我解决了大部分问题,但我现在无法找到插入功能的问题。我在While循环语句中得到分段错误,当我比较插入指针数据和当前指针数据时。我已经查看了我的C书,它有与我类似的代码,也通过Doubly Linked List Segmentation Fault -C问题,但仍然无法得到我的错误。
这是我的输出
-bash-3.2$ ./main 3 100
please enter the process-id, arrival-time and cpu-time.
1 2 3 4
something
something
DONE1
DONE2
DONE3
DONE4
Segmentation fault
因为test4(DONE4)打印而下一次测试没有,这意味着我在这部分中有错误
while((currentptr->arrivaltime < newpointer->arrivaltime) && currentptr != NULL)
你能帮帮我吗?我的代码出了什么问题?
struct event {
struct event *next;
int processid;
int arrivaltime;
int cputime;
};
typedef struct event Event;
typedef Event *eventPtr;
Event create_node(int processid, int arrivaltime, int cputime);
void add_event(Event *newpointer, eventPtr *eventlist);
void print_node(Event node);
void print_eventlist(Event *eventlist);
Event get_nextevent(Event *eventlist);
int main(int argc, char* argv[])
{
int sourcenum,a,b,c,i;
Event tempevent;
eventPtr eventlist = NULL;
print_eventlist(&(*eventlist));
char* sources,timeSlice;
if(argc != 3)
printf("Proper usage is: main.c sources time-slice\n");
else
{
sourcenum = atoi(argv[1]);
timeSlice = atoi(argv[2]);
for(i = 0; i < sourcenum ; i++)
{
//print_eventlist(&(*eventlist));
printf("please enter the process-id, arrival-time and cpu-time.\n");
scanf("%d %d %d",&a, &b, &c);
printf("something\n");
tempevent = create_node(a,b,c);
print
printf("something\n");
add_event(&tempevent, &eventlist);
}
}
return 0;
}
void add_event(Event *newpointer, eventPtr *eventlist) //insert
{
printf("DONE1\n");
eventPtr currentptr, prevptr;
printf("DONE2\n");
prevptr = NULL;
printf("DONE3\n");
currentptr = *eventlist;
printf("DONE4\n");
while((currentptr->arrivaltime < newpointer->arrivaltime) && currentptr != NULL) /*on every loop previous and current pointer gets upgraded*/
{
printf("DONEW\n");
prevptr = currentptr;
currentptr = currentptr->next;
}
printf("DONEW\n");
if(prevptr != NULL)
{
printf("DONEW\n");
prevptr->next = newpointer;
newpointer->next = currentptr;
}
else
{
printf("DONEW\n");
newpointer->next = *eventlist; //?????
*eventlist = newpointer;
}
printf("DONE\n");
}
答案 0 :(得分:1)
您说明问题最有可能出现在
中while((currentptr->arrivaltime < newpointer->arrivaltime) && currentptr != NULL)
您要测试currentptr!=NULL
的事实意味着它可能为NULL。但如果是,那么你病情的早期部分就会失败。首先测试NULL
,然后进行比较的后半部分......:
while(currentptr != NULL && (currentptr->arrivaltime < newpointer->arrivaltime))
答案 1 :(得分:1)
eventPtr eventlist = NULL;
add_event(&tempevent, &eventlist);
{
currentptr = *eventlist; //currentptr == NULL at this point
...............
while(currentptr->arrivaltime ....) // Segmentation
}
在您的代码中,“eventlist = NULL”传递到“add_event”。这就是分割的原因。
我认为你应该在“add_event”中使用“malloc()”来获取“eventlist”的条目。