简体   繁体   中英

How to allocate memory for an array of structs inside of a function in C

For a class assignment I have an array that I need to define in main() but allocate memory and load the data in a sperate function load(). Right now autos[] doesn't get populated with the data from the file. Any help is appreciated.

The struct has 4 fields: name, floatNum, intNum, color, that the data needs to be written to. size and autos[] are both defined in main and size refers to the number of elements in autos[].

Load function

void load(int size, struct data autos[]) {
    
    autos = malloc(size * sizeof(struct data));
   
    FILE *data;
    data = fopen("./hw3.data", "r");
    int i;
    for (i = 0; i < size; i++) {
        fscanf(data, "%s %f %d %s", autos[i].name, &autos[i].floatNum, &autos[i].intNum, autos[i].color);
    }
}

I figured it out. Thank you Craig and Johnathan for giving me some pointers. It takes the size of the array needed (from a different function) and creates one and scans through the data file putting data into each element.

struct data* load(int size){
    
    struct data* autos = malloc(size * sizeof(struct data));  

    FILE* data;
    data = fopen("./hw3.data", "r");

    int i = 0;
    for (i = 0; i < size; i++) {
        fscanf(data, "%20s %f %d %20s", autos[i].name, &autos[i].floatNum, &autos[i].intNum, autos[i].color);
    }

    fclose(data);

    return autos;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM