I am very new to c and pointers. Each time I thin k I have understood it, there comes a problem that I don’t really understand (I spent some time reading c docs but pointers still remain unclear to me) :
typedef struct {
int q[QUEUESIZE+1];
int first;
int last;
int count;
} queue;
enqueue(queue *q, int x)
{
if (q->count >= QUEUESIZE)
printf("Warning: queue overflow enqueue x=%d\n",x);
else {
q->last = (q->last+1) % QUEUESIZE;
q->q[ q->last ] = x;
q->count = q->count + 1;
}
}
I hope my question will not be too opaque but could someone explain the use of pointer in enqueue function? I thought the principle of queuing was to allocate some precise successive memory addresses, but it is not that for sure….
enqueuetakes a queue queue (queue of type queue) and add an element in it (which is made of an integer.queue *qis a pointer, since, probablyenqueuePassing a queue by value, as
would mean
qparameter)qis modified, the modification is made onqwithin theenqueuefunction.The initially provided queue (myqueue) as parameter would not be modified
For instance
Besides, the
enqueuefunction implementation could be optimized… (see wildplasser answer below who suggests a better queue implementation)