The enque function in queue (using linked data structure) is generally used with malloc() function. However , I am trying to implement it little differrntly by avoiding the use of malloc() as follows.
I am printing the value of what holds in the rear twice. It prints the correct value for the first time, however, it gives a garbage value the second time.
void enque(queue* qp, int x) // queue is a struct that holds front and rear node address
{
queueNode a; // queueNode is a struct with data and next pointer
a.data = x;
a.next = NULL;
if(isEmpty(qp))
{
qp->front = &a;
qp->rear = &a;
}
else
{
qp->rear->next = &a;
qp->rear = qp->rear->next;
}
}
The main function
int main()
{
queue q;
int c;
initialize(&q);
enque(&q, 11);
printf("\n %d",(&q)->front->data);
printf("\n %d",(&q)->front->data);
return 0;
}
The output is as follows :
11
some garbage value
Why does it print the garbage value the second time and not 11?