Problem with linked list and strings

Discussion in 'C Programming' started by kalooo, Oct 17, 2010.

  1. kalooo

    kalooo

    Joined:
    Oct 17, 2010
    Messages:
    2
    Hello, i created a linked list but it has problem to put in the nodes the content which get from the gets() function. ie put in all nodes the last input. But the code works correctly in the comments.

    Any idea?

    Here is my 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;

    }
    kalooo, Oct 17, 2010
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Chris Ritchey
    Replies:
    7
    Views:
    466
    emerth
    Jul 10, 2003
  2. Chris Ritchey

    Generating a char* from a linked list of linked lists

    Chris Ritchey, Jul 9, 2003, in forum: C Programming
    Replies:
    7
    Views:
    455
    emerth
    Jul 10, 2003
  3. fool
    Replies:
    14
    Views:
    494
    Barry Schwarz
    Jul 3, 2006
  4. joshd
    Replies:
    12
    Views:
    658
    John Carson
    Oct 2, 2006
  5. jawdoc
    Replies:
    9
    Views:
    738
    Chris Thomasson
    Mar 10, 2008
Loading...

Share This Page