【发布时间】:2017-01-08 17:54:54
【问题描述】:
我已经在 C 中实现了一个简单的队列,但是当我在出队后尝试访问 Q.front 时,它给出了分段错误(例如,参见 int main())。
更准确地说,问题发生在我 -
- 将单个元素排入队列。
- 出队。
- 将一个或多个元素排入队列。
- 尝试访问Q.front
但是当我 -
- 将多个元素加入队列。
- 出队一次。
- 将更多元素加入队列(可选)
- 访问Q.front成功。
所以这是我的完整程序 -
#include <stdio.h>
#include <stdlib.h> //for malloc
struct qnode
{
int r;
struct qnode *link;
};
typedef struct qnode qNode;
typedef struct
{
qNode *front;
qNode *rear;
int qsize;
}QUEUE;
QUEUE initializeQueue(void)
{
QUEUE q;
q.front = NULL;
q.rear = NULL;
q.qsize = 0;
return q;
}
qNode *createQueueNode(int e)
{
qNode *temp;
temp = (qNode *) malloc(sizeof(qNode));
if(temp == NULL)
{
printf("INSUFFICIENT MEMORY\n");
exit(0);
}
temp->r = e;
temp->link = NULL;
return temp;
}
QUEUE enqueue(QUEUE q, int e)
{
if(q.rear == NULL)
{
q.rear = createQueueNode(e);
q.front = q.rear;
q.qsize++;
}
else
{
q.rear->link = createQueueNode(e);
q.rear = q.rear->link;
q.qsize++;
}
return q;
}
QUEUE dequeue(QUEUE q)
{
qNode *temp;
if(q.front == NULL)
{
printf("queue is empty\n");
exit(0);
}
else
{
temp = q.front;
q.front = q.front->link;
free(temp);
}
q.qsize--;
return q;
}
int main(){
QUEUE Q = initializeQueue();
Q = enqueue(Q, 2);
printf("%d\n",Q.front->r);
Q = dequeue(Q);
Q = enqueue(Q,4);
printf("%d\n",Q.front->r); // This line is giving segmentation fault
return 0;
}
【问题讨论】:
标签: c segmentation-fault queue priority-queue