As mentioned by OctaveL, in the function create you try to set the fields of the queue but the pointer passed to the function does not point to a queue, it is uninitialized. If you add the option -Wall to gcc it will actually warn you about this:
$ gcc -o test -Wall test.c
test.c: In function 'main':
test.c:71:5: warning: 'q' is used uninitialized in this function [-Wuninitialized]
create (q);
^~~~~~~~~~
Solution 1: Declare q as a record and pass the address of q to the function create:
struct queue q;
create (&q);
Solution 2: Declare q as a pointer and allocate a new queue variable:
struct queue *q;
q = malloc(sizeof *q);
create(q);
I would also advice you to rename the function create to init or clear since it doesn't create a new queue, it only initializes (or clears) it.
To make memory allocation easier and to handle errors properly it is convenient to introduce two macros:
#define NEW_ARRAY(ptr, n) \
(ptr) = malloc((n) * sizeof (ptr)[0]); \
if ((ptr) == NULL) { \
fprintf(stderr, "Memory allocation failed: %s\n", strerror(errno)); \
exit(EXIT_FAILURE); \
}
#define NEW(ptr) NEW_ARRAY(ptr, 1)
With these in place and if create is renamed to init you can write solution 2 as
struct queue *q;
NEW(q);
init(q);
You didn't allocate memory for q in your main(), so it crashes when attempting to access q->front in create().
int main (void) {
struct queue *q; // No allocation here
...
}
You probably wanted this, which works just fine:
int main (void) {
struct queue q;
create (&q);
enqueue(&q, 5);
}
Try this. Unix comes with several kinds of linked lists - you can use one of them to create other possibly list based structures such as a stack.
man queue
No. But here is a very simple implementation:
typedef struct node {
int val;
struct node *next;
} node_t;
void enqueue(node_t **head, int val) {
node_t *new_node = malloc(sizeof(node_t));
if (!new_node) return;
new_node->val = val;
new_node->next = *head;
*head = new_node;
}
int dequeue(node_t **head) {
node_t *current, *prev = NULL;
int retval = -1;
if (*head == NULL) return -1;
current = *head;
while (current->next != NULL) {
prev = current;
current = current->next;
}
retval = current->val;
free(current);
if (prev)
prev->next = NULL;
else
*head = NULL;
return retval;
}
Complete source here