我用链表编写了一个实现队列的程序..
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
struct queue
{
struct node *front;
struct node *rear;
};
struct queue *q;
void create_queue(struct queue *);
struct queue * insert(struct queue *,int);
struct queue * delete(struct queue *);
struct queue * display(struct queue *);
int peek(struct queue *);
int main()
{
printf("a");
int value,option,t=0;
create_queue(q);
while(t==0)
{
printf("\n1.insert\n2.delete\n3.peek\n4.display\n");
scanf("%d",&option);
switch(option)
{
case 1:
printf("enter the number to be inserted");
scanf("%d",&value);
q=insert(q,value);
break;
case 2:
q=delete(q);
break;
case 3:
value=peek(q);
printf("the value pointed by front is %d",value);
break;
case 4:
q=display(q);
break;
default:
printf("invalid option");
}
printf("\n '0' to run again else '1' \n");
scanf("%d",&t);
}
return 0;
}
void create_queue(struct queue *q)
{
q->rear=NULL;
q->front=NULL;
}
struct queue * insert(struct queue *q,int value)
{
struct node *ptr;
ptr=(struct node *)malloc(sizeof(struct node *));
ptr->data=value;
if(q->front==NULL)
{
q->front=ptr;
q->rear=ptr;
q->front->next=q->rear->next=NULL;
}
else
{
q->rear->next=ptr;
q->rear=ptr;
q->rear->next=NULL;
}
return q;
}
struct queue * delete(struct queue *q)
{
struct node *ptr;
ptr=q->front;
if(q->front==NULL)
printf("\n underflow");
else
{
q->front=q->front->next;
printf("\n the value being deleted is %d",ptr->data);
free(ptr);
}
return q;
}
struct queue * display(struct queue *q)
{
struct node *ptr;
ptr=q->front;
if(ptr==NULL)
printf("\n queue is empty");
else
{
printf("\n");
while(ptr!=q->rear)
{
printf("%d \t",ptr->data);
ptr=ptr->next;
}
printf("%d \t",ptr->data);
}
return q;
}
int peek(struct queue *q)
{
return (q->front->data);
}
执行时: 终端显示“分段故障(核心转储)”并执行程序停止。 为什么会这样? 必须在代码中进行哪些修改才能避免这种情况?
答案 0 :(得分:3)
In addition to the problem pointed out by @FredK in his answer, you are not creating the struct queue
properly.
Since you have defined q
to be in global scope, it is initialized to NULL
. And then you use it as an argument in create_queue
before its value has been set to a valid pointer. In create_queue
, you access the pointer as if it points to a valid object. Accessing members of a NULL pointer cause undefined behavior. In your case, that manifests as segmentation fault.
Change create_queue
to:
struct queue * create_queue()
{
struct queue *q = malloc(sizeof(*q));
q->rear=NULL;
q->front=NULL;
return q;
}
Remove the global variable q
and replace it with a local variable in main
.
int main()
{
struct queue *q;
printf("a");
int value,option,t=0;
q = create_queue();
...
}
答案 1 :(得分:2)
ptr=(struct node *)malloc(sizeof(struct node *));
This is incorrect. You have allocated space for a pointer to a node rather than for a node. To avoid such confusion, always use
ptr = malloc( sizeof(*ptr) );
Don't cast the result of malloc - it will hide the error that you will encounter if you forget to
#include <stdlib.h>