Sign in to follow this  
xllx_relient_xllx

link list problem..

Recommended Posts

I input: mat1, mat2..mat5. The output should be mat1..mat5 but instead it prints: mat5 mat5 mat5 mat5 mat5 Press any key to continue ..It's only printing the last node, why? code: #include <stdio.h> #include <stdlib.h> #include <string.h> #include <windows.h> typedef struct strNode { char *name; struct strNode *next; }node_t; node_t *head, *tail; void addNode(char *value); void printNode(void); main() { head = tail = NULL; char value[7]; int n = 0; while (n < 5) { gets(value); addNode(value); n++; } printNode(); } void addNode(char *value) { node_t *insert; insert = (node_t*)malloc(sizeof(node_t)); insert->name = value; insert->next = NULL; if (head == NULL) head = tail = insert; else { tail->next = insert; tail = insert; } } void printNode(void) { node_t *current; current = head; puts(""); while (current != NULL) { puts(current->name); current = current->next; } }

Share this post


Link to post
Share on other sites
Your nodes are all pointing at the same location in memory, the stack location of your buffer. You need to allocate new memory for each string you put in the nodes. Probably the easiest way to do this, since it looks like you are using pure C is to use the strdup() function. Just don't forget to free the memory when you free the nodes.

Share this post


Link to post
Share on other sites
That function workd perfect. Of course, I could've done value = (char*)malloc(7*sizeof(char)); before gets() but that's too much code when strdup makes it simpler. Anyway, I have one more question; The root problem was that on every call to the function addNode, value, always had the same address. meaning it never changed with every gets(), am I right here?

Thanks alot.

Share this post


Link to post
Share on other sites
Quote:
Original post by xllx_relient_xllx
The root problem was that on every call to the function addNode, value always had the same address. meaning it never changed with every gets(), am I right here?
main()
{
head = tail = NULL;
char value[7];
int n = 0;

while (n < 5) {

gets(value);
addNode(value);
n++;
}

printNode();
}
Yes. The address of value doesn't change while in the function. So, every call to gets() overwrites the string from the previous call, and every call to addnode saves a pointer to the same place. Using strdup() to make a copy of the string, as SiCrane wrote, will solve the problem.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this