About the crashing/listing the elements, I have a few questions as I did some testing using the same structures defined as in the first post.
I used the following code with a temporary variable just like you guys said like this:
Code:
void listQueue(Queue *q) {
Node *ptr;
ptr = q->first;
while(ptr) {
printf("%d", ptr->elem);
ptr = ptr->next;
}
}
This works, I can call this function over and over and it works fine. Then I tested the way you said it would crash, like this:
Code:
void listQueue(Queue *q) {
while(q->first) {
printf("%d", q->first->elem);
q->first = q->first->next;
}
}
This also works, it didn't crash. Well, for some part. I mean, I called listQueue() once and it listed everything without crashing, however, calling it again, crashed with segmentation fault. This was the crashing you were talking about right?
But, this happens because we are passing the queue argument as a pointer and I decided to do it like this instead:
Code:
void listQueue(Queue q) {
while(q.first) {
printf("%d", q.first->elem);
q.first = q.first->next;
}
}
For this to work, I would have to call the function like this, listQueue(*q), instead of, listQueue(q) as in the previous examples. So, isn't this a better way? I have a feeling you are going to say it's not and I should opt for the method with a temporary variable. But why is that method better? What are the differences?