Is there a way to determine how many elements an array of struct should have or allocate dynamic memory for a struct array in C? The code opens a binary file and reads it into a struct array. I can place an arbitrary value like 3000, however when I go to print it gives me the garbage values after the file ends. I'm looking for a way to set my array to the size of the file that is being read or limit it to the useful data. I imagine a function like malloc() just haven't been able to find examples with struct arrays that aren't static.
#include "function.h"
int main() {
FILE *fp; // file pointer
STRUCTNAME structVar[]; //typdef array of structs
fp = fopen("file.bin", "rb"); //binary file to read into array
if(fp == NULL) { // error check file opening
printf("error\n");
} else {
//while !feof to read file into array
while(!feof(fp)) {
fread(structVar, sizeof(structVar), 1, fp);
printStructData(structVar);
}
fclose(fp); // closes file
}
return 0;
}