I've looked around and found answers on how to allocate memory properly for a 2D array with pointer notation, and I've found how to properly pass a 2d pointer array to a function, but I can't seem to combine the two steps.
So logically what I'm trying to do is allocate an array of pointers to structs. What appears to be failing is trying to allocate memory
my code thus far:
typedef struct {
int tax, savings;
float salary;
} employee;
int readRecordFile(char* filename, Record*** array);
int main(void) {
employee** array;
int size;
char* file = "money.csv";
size = readRecordFile(file, &array);
FILE* fptr;
fptr = fopen(file, "r");
//Read the file into the the array
for (int i = 0; i < size; i++) {
fscanf(fptr, "%d,%d,%f", array[i]->tax, array[i]->savings, array[i]->salary);
}
fclose(fptr);
for (int i = 0; i < size; i++) {
printf("%d, %d, %f\n", array[i]->tax, array[i]->savings, array[i]->salary);
}
return 0;
}
int readRecordFile(char* filename, employee*** array) {
//Function to open the file, malloc and initialize 2d arrays
//Open the file
FILE* fileptr;
fileptr = fopen(filename, "r");
if (fileptr == NULL) {
printf("Failed to open file");
exit(-1);
}
//Read first line of file (the size) and store to an int
int n;
fscanf(fileptr, "%d", &n);
//Initial malloc for the array of pointers
**array = malloc(n * sizeof(employee*)); //This is the line that throws the exception
//Malloc for each pointer in the array of pointers
for (int i = 0; i < n; i++) {
*(array+i) = malloc(sizeof(employee));
}
//Close the file and return the size of the file
fclose(fileptr);
return n;
}
I have tried building a separate struct pointer within the function, then setting the regular pointer to it
//Initial malloc for the array of pointers
employee **tester = malloc(n * sizeof(employee*));
//Malloc for each pointer in the array of pointers
for (int i = 0; i < n; i++) {
*(tester+i) = malloc(sizeof(employee));
}
array = tester;
This method appears to fix the malloc issues, but the data printing in main fails.