Marc Romaní
Marc Romaní

Reputation: 126

struct by reference not changing

I'm trying to make a basic linked list in C, I have a struct and an "append" function. However, no matter how many items I add to it, the struct doesn't change at all. I can't find the bug, really.

The struct:

typedef struct list {
    int node;
    struct list *next;
} list_t;

The append function:

void append(list_t *list, int node) {
    if(!list) {
        list = malloc(sizeof(list_t));
        list->node = node;
        list->next = NULL;
    }else {
        list_t *probe = list;
        while(probe->next) probe = probe->next; 
        probe->next = malloc(sizeof(list_t));
        probe = probe->next;
        probe->node = node;
        probe->next = NULL;
    }
}

The print function:

void lprint(list_t *list) {
    if(!list) {
        printf("empty");
    }else {
        list_t *probe = list;
        do {
            printf("%d ", probe->node);
            probe = probe->next;
        } while(probe);
    }
    printf("\n");
}

The main function:

void main() {

    list_t *list = NULL;

    int node;
    for(node = 0; node < 5; node++) {
        append(list, node);
        lprint(list);
    }
}

The output is:

empty
empty
empty
empty
empty

While it should be:

0
0 1
0 1 2
0 1 2 3
0 1 2 3 4

Any help?

Upvotes: 0

Views: 101

Answers (1)

Elazar
Elazar

Reputation: 21585

There is not such thing as "pass by reference" in C. you pass a pointer. by value. If you want to change a pointer, you should pass pointer-to-pointer.

void append(list_t **list, int node) {
    assert(list != NULL);
    if(! *list) {
        *list = malloc(sizeof(list_t));
        (*list)->node = node;
        (*list)->next = NULL;
    ...
}

Note that this is bad design: you should add a function "create", which will create the list. "append" should do exactly this: appending to an already existing list.

Upvotes: 3

Related Questions