简体   繁体   English

如何为 C 中的 function 内部的结构数组分配 memory

[英]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().对于 class 分配,我需要在 main() 中定义一个数组,但分配 memory 并将数据加载到单独的 function load() 中。 Right now autos[] doesn't get populated with the data from the file.现在 autos[] 没有填充文件中的数据。 Any help is appreciated.任何帮助表示赞赏。

The struct has 4 fields: name, floatNum, intNum, color, that the data needs to be written to.该结构有 4 个字段:name、floatNum、intNum、color,需要写入数据。 size and autos[] are both defined in main and size refers to the number of elements in autos[]. size 和 autos[] 都在 main 中定义,size 是指 autos[] 中的元素个数。

Load function加载 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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