【问题标题】:C Passing a list from struct to another functionC将列表从结构传递到另一个函数
【发布时间】:2016-05-01 23:13:33
【问题描述】:

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

#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”。

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

【问题讨论】:

  • 两者都是未定义的行为l = (List*) malloc(sizeof(List)); 不更新调用方变量。

标签: c list struct pass-by-reference


【解决方案1】:

您正在尝试修改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);

虽然现在分配了 Figures 结构 ms,但列表一、二和三是 NULL 并且没有指向任何地方。

【讨论】:

  • 非常感谢!现在它起作用了。我认为在传递 another_function(figures->one) 后,其中figures->one 是指向列表的指针,它可以在另一个函数中更新。
猜你喜欢
  • 1970-01-01
  • 2013-08-19
  • 1970-01-01
  • 2016-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-21
  • 1970-01-01
相关资源
最近更新 更多