当我用debuging检查它时功能正常,但在功能完成后数组是空的
这是结构:
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;
}
这是主要的来电:
{
counter_2=ReadFromFile(pFieldArr);
printf("\nFile loaded successfully!");
New_Field_flag=0;
Exit=0;
break;
}
tnx家伙......
答案 0 :(得分:0)
您正在将指针传递给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;
}
然后:
{
counter_2 = ReadFromFile(&pFieldArr);
printf("\nFile loaded successfully!");
New_Field_flag = 0;
Exit = 0;
break;
}