0

My Structure

struct table_structure{
    char first_name[50];
    char last_name[50];
    char gender;
    char dob[50];
    int waist;
    int hip;
};

Main()

char filename[]="C:/Users/Rustam/Desktop/data.txt";
int i;
struct table_structure *healthcare_table;
healthcare_table=(struct table_structure*)malloc(sizeof(struct table_structure))

Load function. Here I need to load my file to the array of structures. The File looks like this:

enter image description here NOTE: I don't need to take the first row of my file.

int load_Healthcare_Table(char file_name[], struct table_structure a[]){
    FILE *inFILE;
    inFILE=fopen(file_name,"r");
    if(inFILE)printf("File opened successfuly\n");
    else {
        printf("Failed to open the File\n");
        exit(1);
    }
    fseek(inFILE,50L,SEEK_SET);
    int i=1;
    while(fscanf(inFILE,"%s%s\t%c%s%d%d",(*(a+i-1)).first_name,(*(a+i-1)).last_name,&(*(a+i-1)).gender,(*(a+i-1)).dob,&(*(a+i-1)).waist,&(*(a+i-1)).hip)!=EOF){
        i++;
        a=(struct table_structure*)realloc(a,i*sizeof(struct table_structure)); 
    }
};

Now the issue is that my realloc() function is only working local to my load_Healthcare_Table() function. How can I dynamically allocate memory to my array as I read through each row of my file?

  • 1
    Can you edit your post to _[create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve)_? – ryyker May 26 '17 at 18:02
  • You can use `&a[i-1].gender` instead of `&(*(a+i-1)).gender`. – mch May 26 '17 at 18:02
  • 1
    You could pass the allocated pointer back to the caller as the function value, instead of receiving it as a function parameter. If the input fails, `return NULL`. At the now, you are supposed to return `int` but don't return anything. – Weather Vane May 26 '17 at 18:09
  • `struct table_holder { struct table_structure *healthcare_table; int rows; } th;`.. `load_Healthcare_Table(char file_name[], struct table_holder *th);` call `load_Healthcare_Table(filename, &th);` – BLUEPIXY May 26 '17 at 18:09

0 Answers0