airPdata **airport = malloc(sizeof(airport) * (50+1));
printf("Passes airPdata **airport\n");
// buffer = malloc(sizeof(char) * (50+1));
// puts the strings into char line
while(fgets(line, 1024, fp) != NULL)
{
// has pointer value point to line
value = line;
printf("Before creating space for struct members\n");
// creating space for the struct members
airport[j]->LocID = malloc(sizeof(char)*(50+1));
airport[j]->fieldName = malloc(sizeof(char)*(50+1));
airport[j]->city = malloc(sizeof(char)*(50+1));
printf("after\n");
我正在尝试创建一个结构数组,但我无法弄清楚如何为结构的成员分配内存..它保持segfaulting . LocID,fieldName和city都是char *
编辑***我发现了问题 . 使用双指针不需要分配机场,但仍需要分配机场成员 .
//为struct airPdata **机场分配内存;
// buffer = malloc(sizeof(char)*(50 1));
// puts the strings into char line
while(fgets(line, 1024, fp) != NULL)
{
// has pointer value point to line
value = line;
printf("Yes\n");
// creating space for the struct members
airport[j]->LocID = malloc(sizeof(char)*(50+1));
airport[j]->fieldName = malloc(sizeof(char)*(50+1));
airport[j]->city = malloc(sizeof(char)*(50+1));
j++;
}
但是,当程序第二次绕着while循环返回并遇到 airport[j]->LocID = malloc
时,程序会出错 .
2 回答
OP的代码最大的失败是没有为每个
airport[i]
分配内存使用
airPdata **airport
和I want to use an array of pointers,代码需要分配2个级别并使用arrray .数组内存
airport[]
分配并分配给
airport[i]
( OP missed this part. )的每个元素的内存内存已分配并分配给各个成员,如
airport[i].LocID
数组
airport
的内存很简单,如下所示 .airPdata **airport
是指针而不是数组 . 而是使用数组,因为这是规定的设计目标 .现在分配,读取并开始填充数组,根据需要进行分配 .
后来释放了一切
细节:请注意以下细微错误 . 它分配的大小为
airport
,类型为airPdata **
.相反,它应该分配
* airport
的大小,类型为airPdata *
.通常,所有类型的对象指针都具有相同的大小,但是在C中的所有类型中都没有指定相同的指针 .
最好分配到类型的去引用指针的大小 . 它更可能编码正确,更容易审查和维护 .
你正在混合使用两种方法 .
你有一系列连续的机场
B你有一系列指向机场的指针(不一定在内存中彼此相邻)
如果你想要A,你的malloc会混合A和B.
做
如果你想B做
然后,您将不得不为每个指针槽分配一个机场对象 .