这是队列的C程序。我刚刚写入它的插入值。我得到的问题是每次插入第一个元素时出现分段错误。为什么这个程序在这个队列程序中给出了分段错误
#include <stdio.h>
#include <malloc.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);
int main()
{
int val, option;
create_queue(q);
do
{
printf("\n *****MAIN MENU*****");
printf("\n 1. INSERT");
printf("\n Enter your option : ");
scanf("%d", &option);
switch(option)
{
case 1:
printf("\n Enter the number to insert in the queue:");
scanf("%d", &val);
q = insert(q,val);
break;
}
}while(option != 5);
return 0;
}
void create_queue(struct queue *q)
{
q = (struct queue *)malloc(sizeof(struct queue));
q->rear = NULL;//how this happened without any error??
q->front = NULL;
}
struct queue *insert(struct queue *q,int val)
{
struct node *ptr;
ptr = (struct node*)malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("error in allocating\n");
return -1;
}
ptr->data = val;
if(q->front == NULL)
{
q->front = ptr;//here I get segmentation fault
q->rear = ptr;
q->front->next = q->rear->next = NULL;
}
else
{
q->rear->next = ptr;
q->rear = ptr;
q->rear->next = NULL;
}
return q;
}
我的程序有什么问题? 为什么分配一个新节点不起作用,当前的语法是什么?
'create_queue()'使所有本地更改..... –
q是一个指针在这里。所以对其元素的任何更改都将被保存。不是吗? – acidlategamer
在'create_queue'中分配的内存不会返回到任何地方,因此您在未分配时使用q导致未定义的行为。用调试器逐行执行会很容易地显示出来。要么返回指针,要么使用** ** –