when i execute this code and lets say i enter "hello", then "world", and then "dude", when i traverse through the list, it only prints out:
dude
dude
dude
and not this:
dude
world
hello
Any help would be much appreciated!

#include <stdio.h>
#include <stdlib.h>

struct Node {
    void *data;
    struct Node *next;
};

struct List {
    struct Node *head;
};

static inline void initList(struct List *list)
{
    list->head = 0;
}
struct Node *addFront(struct List *list, char *data);

void traverseList(struct List *list0);

int main(){
 // initialize list
    struct List list;
    initList(&list);
    char input[100];
    // test addFront()
    printf("testing addFront(): ");
    int i;
    for (i = 0; i < 3; i++) {
    fgets(input, sizeof(input), stdin);
    addFront(&list, input);
    }
   traverseList(&list);

return 0;
}

struct Node *addFront(struct List *list, char *data)
{
    struct Node *node = (struct Node *)malloc(sizeof(struct Node));
    if (node == NULL)
    return NULL;

    node->data = data;
    node->next = list->head;
    list->head = node;
    return node;
}

void traverseList(struct List *list)
{
    struct Node *node = list->head;
    while (node) {
        node = node->next;
    }
}

Edited 4 Years Ago by corby

It's because node->data = data; stores the address of your variable input into the node during the first pass through the loop.
Next time through the loop you enter a new word into input. Since all you stored is the address of input and not the data itself, the data is now changed.

IOW, in each node, the data element points to the exact same buffer, therefore whatever is stored in the buffer input at the end of the loop is what each node points to.

Key statement above: "all you stored is the address of input and not the data itself".

oh wow thanks! I cant believe I didnt see that. Things can get confusing sometimes with pointers and addresses. Thanks again for the help!

Things can get confusing sometimes with pointers and addresses.

That's for sure.

What can help is drawing a map of the pointers on paper to see if you're using the correct syntax.

This article has been dead for over six months. Start a new discussion instead.