I have written a function Serve to get the front node in the queue and remove it. It is as follows:
void Serve(QueueNode **p,Queue *q)
{
if(QueueEmpty(q))
Error("Queue is empty!");
else
{
if(q->front==q->rear)
{
*p=q->front;
q->front=q->rear=NULL;
}
else{
*p=(q->front);
q->front=q->front->next;
(*p)->next=NULL;
}
}
}
I call it from the main function as follows:
int main() {
QueueNode **p=malloc(sizeof(QueueNode));
Queue *q=CreateQueue();
Append('a',q);
Append('b',q);
Append('c',q);
Append('d',q);
Serve(p,q);
}
While declaring the pointer to pointer QueueNode, if I set it to NULL or leave it uninitialized the program gave me NULL pointer dereference or accessing wrong memory location. I can understand why. But, here, when I create the QueueNode using malloc in this line:
QueueNode **p=malloc(sizeof(QueueNode));
the space allocated is getting wasted when I reassign it to q->front in the Serve function. How can I save this space. Also, I just need a pointer that points to q->front. Thanks !
malloc()probably isn't needed at all, but no way to be sure without having a self-contained example.QueueNode. There is no need to malloc a node. It should beQueueNode* p = NULL.nullptr? You meanNULL?QueueNode **p=malloc(sizeof(QueueNode));this is wrong, no matter what. It should besizeof(QueueNode *)or better justsizeof *p. But then, as I already said, I don't see why you're allocating memory here at all.