I'm trying to load file from non-main function with pointer to pointer (2D matrix) as argument in ANSI C.
Approach with l-value function is correct:
float **loadArray(int *rows, int *columns) {
float **array;
FILE *instream; // input file pointer
char infile[21] = {}; //20 chars max filename length
int i = 0, j = 0; //iterators
printf("filename to load data from: ");
scanf(" %20s", infile);
if (!(instream = fopen(infile, "r"))) {
perror("fopen() error");
exit(-1);
}
fread(rows, sizeof(int), 1, instream);
fread(columns, sizeof(int), 1, instream);
fprintf(stdout, "\narray(%d,%d):", *rows, *columns); //OK
// allocation of vertical array containing rows pointers.
if (!(array = (float**)malloc((*rows) * sizeof(float*)))) {
printf("vertical malloc() error");
exit(-1);
}
for (i = 0; i < (*rows); i++)
// for every row allocate columns space
if (!(array[i] = (float*)malloc((*columns) * sizeof(float)))) {
printf("horizontal malloc() error");
exit(-1);
}
for (i = 0; i < (*rows); i++)
for (j = 0; j < (*columns); j++)
fread((&array[i][j]), sizeof(float), 1, instream);
fclose(instream);
return array;
}
int main() {
int i = 0;
int rows = 0, columns = 0;
float **myarray;
myarray = loadArray(&rows, &columns);
...
for (i = 0; i < rows; i++)
free(myarray[i]);
free(myarray);
}
But I'm trying to be consistent when reading from file and rows
, columns
are passed as addresses to pass the array in the same way:
int loadArray2(float ***array, int *rows, int *columns) {
FILE *instream; // input file pointer
char infile[21] = {}; //20 chars max filename length
int i = 0, j = 0; //iterators
printf("filename to load data from: ");
scanf(" %20s", infile);
if (!(instream = fopen(infile, "r"))) {
perror("fopen() error");
exit(-1);
}
fread(rows, sizeof(int), 1, instream);
fread(columns, sizeof(int), 1, instream);
fprintf(stdout,"\narray(%d,%d):", *rows, *columns); //OK
// allocation of vertical array containing rows pointers.
if (!(*array = (float**)malloc((*rows) * sizeof(float*)))) {
printf("vertical malloc() error");
exit(-1);
}
for (i = 0; i < (*rows); i++)
// for every row allocate columns space
if (!(*array[i] = (float*)malloc((*columns) * sizeof(float)))) {
printf("horizontal malloc() error");
exit(-1);
}
for (i = 0; i < (*rows); i++)
for (j = 0; j < (*columns); j++)
fread((array[i][j]), sizeof(float), 1, instream);
fclose(instream);
return 0;
}
int main() {
int rows = 0, columns = 0;
float **myarray;
loadArray2(&myarray, &rows, &columns);
...
for (i = 0; i < rows; i++)
free(myarray[i]);
free(myarray);
}
But this approach failed.
I guess I made mistake in malloc()
calling either no error or warnings,
or my logic is bad, I admit I'm lost...
Thanks for some tips.