通过引用而不改变的结构

时间:2013-05-23 22:55:53

标签: c struct

我正在尝试用C创建一个基本的链表,我有一个结构和一个“追加”函数。但是,无论我添加多少项,结构都不会发生变化。我真的找不到这个bug。

结构:

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

追加功能:

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;
    }
}

打印功能:

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");
}

主要功能:

void main() {

    list_t *list = NULL;

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

输出结果为:

empty
empty
empty
empty
empty

虽然它应该是:

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

任何帮助?

1 个答案:

答案 0 :(得分:3)

在C.传递指针时没有“通过引用传递”这样的东西。按价值。如果要更改指针,则应将指针传递给指针。

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

请注意,这是一个糟糕的设计:你应该添加一个“create”函数,它将创建列表。 “append”应该这样做:附加到已有的列表中。

相关问题