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 *
编辑***我发现了问题所在。使用双指针不需要分配机场,但是仍然需要分配机场的成员。
//为struct airPdata ** airport分配内存;
//缓冲区= 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
OP的代码最大的失败是没有为每个分配内存 airport[i]
使用airPdata **airport
和我要使用一个指针数组,代码需要在2个级别分配并使用一个错误。
数组的airport[]
内存分配和分配给airport[i]
(OP错过了这一部分的每个元素)的
内存分配和分配给各个成员的内存,例如airport[i].LocID
数组存储airport
很容易,如下所示。airPdata **airport
是一个指针,而不是一个数组。而是使用数组,因为这是既定的设计目标。
// define array element count.
#define AIRPORT_N 100
// Declare the array.
airPdata *airport[AIRPORT_N];
// Keep tack of how much of the array is used.
size_t n = 0;
现在分配,读取并开始填充数组,并根据需要进行分配。
#define AIRPORT_STRING_SIZE (50 + 1)
char line[1024];
while(n < AIRPORT_N && fgets(line, sizeof line, fp)) {
// Allocate memory for one element of `airport`
// Notice no cast nor type coded here.
airport[n] = malloc(sizeof *(airport[n]));
if (airport[n] == NULL) {
// Something simple for now.
fprintf(stderr, "OOM\n");
break;
}
// Create space for each string,
// TODO: add check for Out-of-Memory
airport[n]->LocID = malloc(AIRPORT_STRING_SIZE);
airport[n]->fieldName = malloc(AIRPORT_STRING_SIZE);
airport[n]->city = malloc(AIRPORT_STRING_SIZE);
// Code to parse `line` into `airport[n]` members.
// Usually the parsing happens first and if successful, the above allocations occur.
// If the `LocID` string (and others) need not change then
// use below to allocate a right-sized memory
// after parsing instead of allocating to some max size, like above.
airport[n]->LocID = strdup(LocID_string);
n++;
}
以后释放所有
for (size_t i = 0; i < n; i++) {
free(airport[i]->LocID);
free(airport[i]->fieldName);
free(airport[i]->city);
free(airport[i]);
}
详细信息:请注意以下细微的错误。它分配给airport
type的大小airPdata **
。
相反,它应该分配给* airport
type的大小airPdata *
。
通常,所有类型的对象指针的大小都相同,但是并未在C中的所有类型中指定这种相同性。
最好将分配给类型的取消引用指针的大小分配给该类型。它更可能编码正确,更易于检查和维护。
// airPdata **airport = malloc(sizeof(airport) * (50+1));
airPdata **airport = malloc(sizeof *airport * (50+1));
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句