I'm trying to open a file that has dimensions and values for two matrices. I want to store the dimensions of the matrices, and create three 2D int arrays with those read from the file (the third is the result of matrix multiplication). I'm passing a pointer to an int pointer for the argument, hence why the parameters for the read_matrices method are int** (assignment requirement).
I keep getting a segmentation fault during the malloc portion of my code, but can't figure out the problem. It seems to work for the first two matrices, and I can get the first printf statement to print during the malloc for array3, but I get a segmentation fault before the second printf statement. I assume there's something wrong in the loop, but I can't figure it out, especially because it seems to work for the malloc of array1 and array2 (unless the whole thing is wrong). Any help is appreciated.
Edit: Edited to include only the most important portions of the code
void read_matrices(int **array1, int **array2, int **array3, int *m, int *n, int *p, char* file)
{
/* Get the size of the matrices */
fscanf(fp, "%d", m);
fscanf(fp, "%d", n);
fscanf(fp, "%d", p);
/* Use malloc to allocate memory for matrices/arrays A, B, and C */
array1 = (int**) malloc(*m * (sizeof(int*)));
for (i = 0; i < *m; i++)
{
*(array1 + i) = (int*) malloc(*n * (sizeof(int)));
}
array2 = (int**) malloc(*n * (sizeof(int*)));
for (i= 0; i < *n; i++)
{
*(array2 + i) = (int*) malloc(*p * (sizeof(int)));
}
array3 = (int** ) malloc(*m * (sizeof(int*)));
for (i= 0; i < *m; i++)
{
*(array3 + i) = (int *) malloc(*p * (sizeof(int)));
printf("Going through malloc3 loop\n");
}
printf("End of the third part of malloc\b");
/* Close the stream */
fclose(fp);
}
int main (int argc, char *argv[])
{
/* Int pointers to three matrices */
int *A, *B, *C;
/* Int variables to store matrix dimensions */
int m, n, p;
/* Get the name of the file */
char* filename = *(argv + 1);
/* Read the matrices and fill matrices A and B */
read_matrices(&A, &B, &C, &m, &n, &p, filename);
/* Exit the system */
return 0;
}