This is the C program for queue. I have just written it for insert values. The problem I am getting is I get segmentation fault whenever I insert the first element.
#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;
}
what is wrong with my program? Why the assignment of a new node does not work, what is the current syntax?