Struct 将结构从文件返回到结构数组时出现问题
当我通过调试检查函数时,该函数工作正常,但在函数完成后,数组为空 这是结构:Struct 将结构从文件返回到结构数组时出现问题,struct,Struct,当我通过调试检查函数时,该函数工作正常,但在函数完成后,数组为空 这是结构: typedef struct coordinates { int x_l; int y_l; int x_r; int y_r; } Coordinates; typedef struct field { int Id; Coordinates location; int area; int price; } Field; 这就是功能: int ReadFromFile(Field *pArr) {
typedef struct coordinates
{
int x_l;
int y_l;
int x_r;
int y_r;
} Coordinates;
typedef struct field
{
int Id;
Coordinates location;
int area;
int price;
} Field;
这就是功能:
int ReadFromFile(Field *pArr)
{
int size;
int i;
FILE *f = fopen("c:\\migrashim\\migrashim.txt", "r");
if (f == NULL)
{
printf("error open file");
exit (1);
}
fseek(f,0,SEEK_SET);
fscanf(f, "%d\n", &size);
pArr=(Field*)realloc(pArr,sizeof(Field)*(size));
for (i=0 ; i<size ; i++)
{
fscanf(f, "%d\n", &pArr[i].Id);
fscanf(f, "%d %d\n", &pArr[i].location.x_l,&pArr[i].location.y_l);
fscanf(f, "%d %d\n", &pArr[i].location.x_r,&pArr[i].location.y_r);
}
return size;
}
tnx伙计们…您正在将指针传递到ReadFromFile并调整大小 realloc将尝试就地调整大小,但如果不能,它将分配一个新块,复制现有数据,然后释放旧块 您的函数没有考虑到块可能已经移动(您没有返回realloc返回的指针) 编辑: 代码应该如下所示:
int ReadFromFile(Field **pArr)
{
int size;
int i;
FILE *f = fopen("c:\\migrashim\\migrashim.txt", "r");
if (f == NULL)
{
printf("error open file");
exit (1);
}
fscanf(f, "%d\n", &size);
*pArr = (Field*)realloc(*pArr, sizeof(Field)* size);
for (i = 0; i < size; i++)
{
fscanf(f, "%d\n", &(*pArr)[i].Id);
fscanf(f, "%d %d\n", &(*pArr)[i].location.x_l, &(*pArr)[i].location.y_l);
fscanf(f, "%d %d\n", &(*pArr)[i].location.x_r, &(*pArr)[i].location.y_r);
}
fclose(f);
return size;
}
你能举个例子吗。。?
int ReadFromFile(Field **pArr)
{
int size;
int i;
FILE *f = fopen("c:\\migrashim\\migrashim.txt", "r");
if (f == NULL)
{
printf("error open file");
exit (1);
}
fscanf(f, "%d\n", &size);
*pArr = (Field*)realloc(*pArr, sizeof(Field)* size);
for (i = 0; i < size; i++)
{
fscanf(f, "%d\n", &(*pArr)[i].Id);
fscanf(f, "%d %d\n", &(*pArr)[i].location.x_l, &(*pArr)[i].location.y_l);
fscanf(f, "%d %d\n", &(*pArr)[i].location.x_r, &(*pArr)[i].location.y_r);
}
fclose(f);
return size;
}
{
counter_2 = ReadFromFile(&pFieldArr);
printf("\nFile loaded successfully!");
New_Field_flag = 0;
Exit = 0;
break;
}