我正在尝试实现 FIFO。代码编译没有错误,但在运行程序时出现 segmentation fault
。有什么问题?
#include <stdio.h>
#include <stdlib.h>
struct cell
{
int element;
struct cell *next;
};
struct queue
{
struct cell *front;
struct cell *rear;
};
void enqueue(int x, struct queue *Q);
void dequeue(struct queue *Q);
main()
/* Manipulation of a linked queue of cells. */
{
struct queue *Q;
struct cell *q;
int i;
Q->front=Q->rear=NULL;
for(i=0; i<8; i++) {enqueue(i+1, Q);}
printf("Q->front = %p, Q->rear = %p\n", Q->front, Q->rear);
q=Q->front;
while(q!=NULL)
{
printf("cell = %d, %p\n", q->element, q->next);
q=q->next;
}
for(i=0; i<10; i++) dequeue(Q);
printf("Q->front = %p, Q->rear = %p\n", Q->front, Q->rear);
q=Q->front;
while(q!=NULL)
{
printf("cell = %d, %p\n", q->element, q->next);
q=q->next;
}
return(0);
}
void enqueue(int x, struct queue *Q)
{
struct cell *p;
p=(struct cell *)malloc(sizeof(struct cell));
if(Q->rear != NULL) Q->rear->next = p;
Q->rear = p;
if(Q->front == NULL) Q->front = p;
Q->rear->element = x; Q->rear->next = NULL;
return;
}
void dequeue(struct queue *Q)
{
struct cell *q;
if(Q->front == NULL) {printf("Error: Queue is empty.\n"); exit(1);}
else {q=Q->front; Q->front = Q->front->next; free(q);}
if(Q->front == NULL) Q->rear = NULL;
return;
}
最佳答案
您没有为 Q
分配内存并立即使用它:
struct queue *Q; /* Where does Q point ? */
Q->front=Q->rear=NULL; /* Q not initialized, undefined behavior */
所以 Q 指向堆栈上的某个随机值。要解决它,请使用 malloc
:
struct queue *Q;
Q = malloc(sizeof(*Q));
if (NULL == Q) {
/* Tinfoil hat. */
}
关于c - 使用指针 : segmentation error 实现队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6579456/