How JustAnswer Works:
  • Ask an Expert
    Experts are full of valuable knowledge and are ready to help with any question. Credentials confirmed by a Fortune 500 verification firm.
  • Get a Professional Answer
    Via email, text message, or notification as you wait on our site.
    Ask follow up questions if you need to.
  • 100% Satisfaction Guarantee
    Rate the answer you receive.
Ask Ingo U Your Own Question
Ingo U
Ingo U, Software Engineer
Category: Programming
Satisfied Customers: 755
Experience:  Over 25 years experience in software development. Expert in Microsoft .Net, C#, C++, VB, SQL
44076068
Type Your Programming Question Here...
Ingo U is online now

This linked list in c works fine but not ,

Resolved Question:

This linked list in c works fine for integers but not for strings, it just keeps printing out the last node:
#include
struct node {
char *str;
struct node *next;
};
int main() {
char text[80];
struct node *root;
struct node *trav;
root = (struct node*)malloc(sizeof(struct node));
printf("Enter string: ");
scanf("%s", &text);
root -> str = text;
trav = root;
trav -> next = (struct node*)malloc(sizeof(struct node));
trav = trav -> next;
printf("Enter string: ");
scanf("%s", &text);
trav -> str = text;
trav -> next = 0;
trav = root;
while(trav != 0) {
printf("%s ", trav -> str);
trav = trav -> next;
}
return 0;
}
Submitted: 2 years ago.
Category: Programming
Expert:  Ingo U replied 2 years ago.
Hi,
you are re-using the same text buffer for both elements. Since each node stores a pointer to a string, they both point to the same string. Your second scanf call overwrites the contents of the text array, so both nodes look like they have the same string, the last one you entered.
You'll need to allocate a separate string buffer for each node you're going to use.
Regards,
Ingo U
Customer: replied 2 years ago.

I'd pay extra if you could tell me how I could flush the buffer effectively so I could reuse the same string variable (so I could use it in a loop)?

Expert:  Ingo U replied 2 years ago.
OK, I'll write some code to illustrate.
Expert:  Ingo U replied 2 years ago.
Here is a modified version of your file:
https://www.dropbox.com/s/ebfs0hv4x95n5pl/LinkedList.c?dl=0
It's still uploading at the moment, hopefully finished by the time you see this.
Let me know if I can be of further assistance. I imagine you might have other questions, I'm here to help.
regards,
Ingo U
Ingo U and 2 other Programming Specialists are ready to help you
Customer: replied 2 years ago.

Thank you for the code you have written. It has answered my question. It just remains for me to rate you with the best rating.

Expert:  Ingo U replied 2 years ago.
Thanks for the positive rating! Please feel free to request me directly at
http://www.justanswer.com/computer/expert-ingou/
if you'd like to work with me on a future project.
Regards,
Ingo

Related Programming Questions