Hi,
I have just learned linked lists on C and want to write a program about it. But even this simple code gives runtime error which I added as attachment.
Could you help me about it, thanks...
Hi,
I have just learned linked lists on C and want to write a program about it. But even this simple code gives runtime error which I added as attachment.
Could you help me about it, thanks...
First, I want to point out that malloc is in stdlib.h, but you aren't including it.
As for the problem, it's because head->next != NULL. You never initialize it to anything, so the program think it's valid.
The next pointer in head needs to be set to NULL after the first malloc:
head->next = NULL;
Why not just write out your values like this?
Code:while(current != NULL){ if(current->coef != 0) printf("%dx%d+",current->coef,current->pow); current = current->next; }
wipe on -A slap on the hand is better than a slap on the face. A tragic lesson learned far too late in life.- wipe off
Ok, the blue sections are your code and won't be explained. The green is mine and I will explain.Code:while(current != NULL){ if(current->coef != 0) printf("%dx%d+",current->coef,current->pow); current = current->next; }
When you are reading in the values you are taking in a final value with a coefficient of 0. You allow it in the list, but you technically only use it to let your program know when to stop reading in new values. Ok, that is fine. Given that fact, why even print something that is basically just a signal to stop reading? So the if statement checks if the coefficient is zero. If the coefficient is zero, the term is skipped.
wipe on -A slap on the hand is better than a slap on the face. A tragic lesson learned far too late in life.- wipe off