By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,968 Members | 1,843 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,968 IT Pros & Developers. It's quick & easy.

Problem with linked list and strings

P: 1
Expand|Select|Wrap|Line Numbers
  1. #include <stdio.h>    /* for printf */
  2. #include <stdlib.h>   /* for malloc */
  3. #include <string.h>
  4.  
  5. struct node
  6. {
  7.     char *data;
  8.     struct node *next; /* pointer to next element in list */
  9. };
  10.  
  11.  
  12.  
  13. struct node *list_add(struct node **p, char *i)
  14. {
  15.     struct node *n = (node *)malloc(sizeof(struct node));
  16.     if (n == NULL)
  17.         return NULL;
  18.  
  19.     n->next = *p; /* the previous element (*p) now becomes the "next" element */
  20.     *p = n;       /* add new empty element to the front (head) of the list */
  21.     n->data = i;
  22.  
  23.     return *p;
  24. }
  25.  
  26.  
  27. void list_print(struct node *n)
  28. {
  29.     if (n == NULL)
  30.     {
  31.         printf("list is empty\n");
  32.     }
  33.     while (n != NULL)
  34.     {
  35.         printf("print %s\n", n->data);
  36.         n = n->next;
  37.     }
  38. }
  39.  
  40. int main(void)
  41. {
  42.  
  43.     int i;
  44.     char buf[1024];
  45.     struct node *n = NULL;
  46.  
  47.     for (i=0;i<5;i++){
  48.  
  49.         gets(buf);
  50.  
  51.         list_add(&n, buf);
  52.      }
  53.  
  54.     //list_add(&n, "aa"); 
  55.     //list_add(&n, "bb"); 
  56.     //list_add(&n, "cc"); 
  57.     //list_add(&n, "dd"); 
  58.     //list_add(&n, "ee"); 
  59.     list_print(n);
  60.  
  61.  
  62.  
  63.  
  64.     return 0;
  65.  
  66. }
  67.  
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?
Oct 16 '10 #1
Share this question for a faster answer!
Share on Google+

Post your reply

Sign in to post your reply or Sign up for a free account.