Problem with linked list and strings

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Tom Avens
    New Member
    • Oct 2010
    • 1

    #1

    Problem with linked list and strings

    Code:
    #include <stdio.h>    /* for printf */
    #include <stdlib.h>   /* for malloc */
    #include <string.h>
     
    struct node
    {
    	char *data;
    	struct node *next; /* pointer to next element in list */
    };
     
    
    
    struct node *list_add(struct node **p, char *i)
    {
    	struct node *n = (node *)malloc(sizeof(struct node));
    	if (n == NULL)
    		return NULL;
     
    	n->next = *p; /* the previous element (*p) now becomes the "next" element */
    	*p = n;       /* add new empty element to the front (head) of the list */
    	n->data = i;
     
    	return *p;
    }
    
    
    void list_print(struct node *n)
    {
    	if (n == NULL)
    	{
    		printf("list is empty\n");
    	}
    	while (n != NULL)
    	{
    		printf("print %s\n", n->data);
    		n = n->next;
    	}
    }
     
    int main(void)
    {
        
        int i;
        char buf[1024];
        struct node *n = NULL;
     
        for (i=0;i<5;i++){
    
            gets(buf);
            
            list_add(&n, buf);
         }
    
    	//list_add(&n, "aa"); 
    	//list_add(&n, "bb"); 
    	//list_add(&n, "cc"); 
    	//list_add(&n, "dd"); 
    	//list_add(&n, "ee"); 
    	list_print(n);
    	
    	
     
        
    	return 0;
    	
    }
    I have this code and it put to all nodes the last input of gets(). However the code in comments(if i don't use gets()) works correctly.

    Any idea?
    Last edited by MMcCarthy; Oct 17 '10, 09:12 PM. Reason: added code tags
Working...