Bil*_*ly 1 c malloc pointers memory-management structure
我有两个结构父母和孩子,你可以在下面的代码中看到.父结构有一个类型为child的指针数组.程序进入for循环时出现segmetation错误.我的代码有什么问题吗?我不想使用方括号的原因是我有一个函数,它接受类型为child的指针参数,我希望将每个子指针传递给该函数,而不需要使用&.
任何帮助将不胜感激谢谢
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct {
int id;
} child;
typedef struct {
child** c;
} parent;
int main(int argc, char **argv) {
int number_of_children = 5;
parent* p = (parent*)malloc(sizeof(parent));
p -> c = (child **) malloc(number_of_children * sizeof(child*));
int i;
for(i=0; i<number_of_children; i++)
p -> c[i] -> id = i;
}
Run Code Online (Sandbox Code Playgroud)
您正在正确分配子指针表,但您没有分配任何子项.
int i
for(i = 0; i < number_of_children; ++i) {
p->c[i] = (child *) malloc(sizeof(child));
p -> c[i] -> id = i
}
Run Code Online (Sandbox Code Playgroud)