有人能解释一下发生了什么吗?此代码工作正常:
#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“。
它适用于一两个列表,但是当我添加第三个或更多的列表时,会出现一些问题。为什么?
发布于 2016-05-01 23:30:54
您正在尝试修改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);虽然现在分配了数字结构ms,但是列表1、2和3都是空的,并且没有指向任何地方。
https://stackoverflow.com/questions/36973043
复制相似问题