首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C将列表从struct传递到另一个函数

C将列表从struct传递到另一个函数
EN

Stack Overflow用户
提问于 2016-05-01 23:13:33
回答 1查看 36关注 0票数 0

有人能解释一下发生了什么吗?此代码工作正常:

代码语言:javascript
复制
#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“。我再增列第三份清单:

代码语言:javascript
复制
#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“。

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-05-01 23:30:54

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

代码语言:javascript
复制
l = (List*) malloc(sizeof(List));

使用指向指针的指针:

代码语言:javascript
复制
void another_function(List **l) {
    *l = (List*) malloc(sizeof(List));
    ...
void function(Figures *figures) {
    another_function(&figures->one);
}    

小心:

代码语言:javascript
复制
Figures ms;
function(&ms);

虽然现在分配了数字结构ms,但是列表1、2和3都是空的,并且没有指向任何地方。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36973043

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档