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);
}
}
struct data *load(int size);orint load(int size, struct data **p_autos)where your calling code hasstruct data *autos;and you pass&autosto the function. If the memory allocation fails (or the file open fails), you should return a null pointer.struct autos **p_autosand it seems that you're usingstruct autos (*autos)— there's a major difference (and the relevant difference isn't the redundant parentheses)! But maybe the problem is SO's use of MarkDown. Use back quotes around code fragments in comments to avoid*being interpreted as formatting — start/stop italic/bold etc. So, type`void load(int size, struct data *(*autos)) …`to get the code formatted better, if that's what you meant.fopensucceeds and that each call tofscanfreturns 4. You also want to limit the scans with egfscanf(data, "%31s %f %d %31s" ...)(assuming the size of each field is not less than 32). You may also want a width modifier on the %f and %d to avoid undefined behavior for inputs that overflow the type, but that's probably overkill at this point. Checking the values returned byfopenandfscanfis essential, however.