开发者

problem with returning struct from file to array of structs

the function work ok while i checked it with debuging but after the function finish the array is empty

this is the structs:

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;

this is the function:

    int ReadF开发者_StackOverflowromFile(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;
    }

and this is the calling from the main:

 {
    counter_2=ReadFromFile(pFieldArr);
    printf("\nFile loaded successfully!");
        New_Field_flag=0;           
        Exit=0;
        break;
 }

tnx guys...


You're passing a pointer into ReadFromFile and resizing.

That realloc will try to resize in-place, but if it can't, it'll allocate a new block, copy the existing data, and then free the old block.

Your function doesn't take into account that the block may have moved (you're not returning the pointer which returned by realloc).

EDIT:

The code should look something like this:

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;
}

and then:

{
    counter_2 = ReadFromFile(&pFieldArr);
    printf("\nFile loaded successfully!");
    New_Field_flag = 0;
    Exit = 0;
    break;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜