0

C で基本的なリンク リストを作成しようとしています。構造体と「追加」関数があります。しかし、いくら項目を追加しても、構造体はまったく変化しません。本当にバグが見つかりません。

構造体:

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

何か助けはありますか?

4

1 に答える 1

3

Cには「参照渡し」というものはありません。ポインタを渡します。値によって。ポインタを変更したい場合は、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;
    ...
}

これは悪い設計であることに注意してください: リストを作成する関数 "create" を追加する必要があります。「追加」はまさにこれを行う必要があります。既存のリストに追加します。

于 2013-05-23T22:57:57.207 に答える