【发布时间】:2018-09-24 03:16:04
【问题描述】:
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");
我正在尝试创建一个结构数组,但我只是不知道如何为结构的成员分配内存。它不断出现段错误。 LocID、fieldName和city都是char*
编辑*** 我解决了这个问题。使用双指针不需要分配机场,但机场的成员仍然需要分配。
// 为结构分配内存 airPdata **机场;
// 缓冲区 = 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 时,程序 seg 出现错误
【问题讨论】:
-
airPdata *airport = malloc(sizeof(*airport) * (50+1));不是** -
我原来用的是airPdata airport[MAX];因为我想使用一个结构数组,但是把它改成了双指针
-
airPdata *airport[MAX]是指针数组,而不是结构数组 -
下定决心——airport 可以是一个指针数组,你先分配然后再分配每个元素;或者它可以只是一个扁平的结构数组,分配一次(然后使用 airport[i].city 而不是 ->)
-
我想使用指针数组,而不是结构,抱歉
标签: c memory-management struct dynamic-memory-allocation