I am trying to learn data structures and I am struggling with getting this code to work. Problem is I am getting segmentation fault(core dumped)
with gcc C compiler. It is supposed to be a queue. The code:
#include <stdio.h>
#include <stdlib.h>
#define STACK_SIZE 50
struct node{
int data;
struct node * next;
};
struct queue{
int count;
struct node * rear ,* front;
};
void create (struct queue * q) {
q -> front = NULL;
q -> rear = NULL;
q -> count = 0;
}
int isempty(struct queue * q) {
if(q -> count == 0)
return 1;
return 0;
}
int full(struct queue * q) {
if(q -> count == STACK_SIZE) {
return 1;
}
return 0;
}
void enqueue(struct queue * q , int x) {
struct node * temp;
temp = (struct node*) malloc(sizeof(struct node));
temp -> data = x;
temp -> next = NULL;
if (full(q)) {
printf("Not possible. Overflow.");
}
else if(isempty(q)) {
q -> front = q -> rear = temp;
} else {
q -> rear -> next = temp;
q -> rear = temp;
}
q -> count++;
}
int dequeue (struct queue * q) {
struct node * p;
p = (struct node*) malloc (sizeof(struct node));
p = q -> front;
if(isempty(q)) {
printf("Not possible. Underflow.");
} else {
q -> front = q -> front -> next;
q -> count--;
}
int x = (p -> data);
return x;
}
int main (void) {
struct queue *q;
create (q);
enqueue(q, 5);
}
The problem is most probably usage of pointers. I've reviewed it a few times but no solution. Valgrind and gdb debuggers weren't much of a help, either.