I read a text file and store the contents in a 2D array called H inside a function, I need to return this 2D array to main somehow so I can use it there and pass it to other functions. I'm not sure how to get the return to work, maybe using pointers. I made the readTxtFile function into a void function to test if the file reading was working (it does) but I can't do anything with the 2D array outside the function. I have two functions getRows() and getCols() that I didn't show here, I can if needed though.
Heres my code so far:
int main(void){
// int *H;
// H = readTxtFile("H.txt");
readTxtFile("H.txt");
return 0;
}
void readTxtFile(char *filename){
int rows, cols;
FILE *fp = fopen(filename, "r");
if (!fp){
perror("can't open H.txt\n");
//return EXIT_FAILURE;
}
rows = getRows(fp);
cols = getCols(fp);
int (*H)[cols] = malloc(sizeof(int[rows][cols]));
if(!H){
perror("fail malloc\n");
exit(EXIT_FAILURE);
}
for(int r = 0; r < rows; ++r){
for(int c = 0; c < cols; ++c){
if(EOF==fscanf(fp, "%d", &H[r][c])){
fprintf(stderr, "The data is insufficient.\n");
free(H);
exit(EXIT_FAILURE);
}
}
}
fclose(fp);
// printH(rows,cols,H);
// return H;
}
This is what the text file looks like:
1 1 0 1 0 0
0 1 1 0 1 0
1 0 0 0 1 1
0 0 1 1 0 1
2 2 2 2 2 2
Any help would be appreciated