Please help me find the mistake.
I was trying to make a circular queue in which the size of the queue as well as the elements inside of the queue are user defined. The code works fine when I am not using loop but as soon as I use the loop it starts showing segmentation fault. enter image description here
#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node *next;
};
typedef struct node node;
typedef struct{
node *head;
node *tail;
} queue;
void createqueue(queue *q){
q->head = NULL;
q->tail = NULL;
return;
}
int enqueue(queue *q, int value){
node *newnode = malloc(sizeof(node));
if (newnode==NULL) return 0;
newnode->data = value;
newnode->next = NULL;
if(q->tail!=NULL){
q->tail->next = newnode;
}
q->tail = newnode;
q->tail->next = q->head;
if(q->head == NULL){
q->head=newnode;
}
return 1;
}
int dequeue(queue *q){
if (q->head==NULL) return 0;
q->head = q->head->next;
q->tail->next = q->head;
return 1;
}
int display(queue *q){
node *printval;
printval = q->head;
if(printval==NULL) return 0;
printf("\n");
do
{
printf("%d-->",printval->data);
printval = printval->next;
} while (printval!=q->head);
}
int main(){
queue *root;
createqueue(root);
printf("Enter the size of the queue");
int size;
scanf("%d",&size);
for(int i=0;i<size;i++){
int value;
printf("Enter the value of the %d element",i);
scanf("%d",&value);
enqueue(root,value);
}
display(root);
}
In a function createqueue
you use a pointer to an object for which memory was not allocated. You need to call malloc first and then set head and tail to a null.
queue* createQueue()
{
queue* q = malloc(sizeof(queue));
if (q != NULL) {
q->head = NULL;
q->tail = NULL;
}
return q;
}
// ...
int main()
{
queue* q = createQueue();
// ...
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments