C 将列表从结构传递给另一个函数

C Passing a list from struct to another function

任何人都可以向我解释发生了什么事吗? 此代码工作正常:

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

typedef struct def_List List;

struct def_List {
    int x;
    int y;
    List *next;
};

typedef struct def_Figures {
    List *one;
    List *two;
} Figures;

void another_function(List *l) {
    l = (List*) malloc(sizeof(List));
    l->x = 1;
    l->next = NULL;
}

void function(Figures *figures) {
    another_function(figures->one);
}

int main() {
    Figures ms;
    function(&ms);
    printf("%d",ms.one->x);
    return 0;
}

打印“1”。 我添加第三个列表:

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

typedef struct def_List List;

struct def_List {
    int x;
    int y;
    List *next;
};

typedef struct def_Figures {
    List *one;
    List *two;
    List *three;
} Figures;

void another_function(List *l) {
    l = (List*) malloc(sizeof(List));
    l->x = 1;
    l->next = NULL;
}

void function(Figures *figures) {
    another_function(figures->one);
}

int main() {
    Figures ms;
    function(&ms);
    printf("%d",ms.one->x); // 1
    return 0;
}

打印“-1992206527”。

它适用于一个或两个列表,但当我添加第三个或更多列表时,出现问题。为什么?

您正在尝试修改 another_function(List *l) 的参数:

l = (List*) malloc(sizeof(List));

改用指向指针的指针:

void another_function(List **l) {
    *l = (List*) malloc(sizeof(List));
    ...
void function(Figures *figures) {
    another_function(&figures->one);
}    

注意:

Figures ms;
function(&ms);

虽然图 struct ms 现在已分配,但列表一、二和三为空且未指向任何位置。