Cyka bLyat Cyka bLyat - 4 months ago 24
C Question

Accessing malloc'd 2-D array in C

I have a function read_mat() that needs to read from a file and put values into a 2-d array that is passed by reference as an argument. After correctly allocating memory for it using malloc(), I have trouble putting in values to the array in the second to last positions. Its of size N x M, where N is rows and M is columns.

I seg-fault after trying to access a[0][3], which I would think should be the last column of the first row but apparently it doesn't exist in memory?? Using stdio.h, stdlib.h and my "header.h" file.

Edit: n = 3, m = 4

int read_mat(int *n, int *m, double ***a) {

//open file
FILE *fp = fopen("matrix.dat", "r");
if (fp == NULL) {
fprintf(stderr, "File open failed!\n");
return -1;
}

//scan first line for size
fscanf(fp, "%d %d", n, m);

//TESTING
printf("Size of n(rows): %d\n", *n);
printf("Size of m(columns); %d\n", *m);

//malloc 1-d array of n # pointers
*a = malloc(*n * sizeof(double*));

//malloc space for m # of columns per row
for (int i = 0; i < *n; i++) {
(*a)[i] = malloc(*m * sizeof(double));
}

//TESTING
fprintf(stderr, "passed malloc!\n");

//scan values and fill array
//rows loop
for (int i = 0; i < *n; i++) {
printf("value of i: %d\n", i);
//column loop
for (int j = 0; j < *m; j++) {
printf("value of j: %d\n", j);
fscanf(fp, "%lf", a[i][j]);
printf("accessed a[%d][%d]!\n", i, j);
}
}

Answer

The line

fscanf(fp, "%lf", a[i][j]);

is wrong. This accesses ith element of a and may be invalid when i>0. What you want should be

fscanf(fp, "%lf", &(*a)[i][j]);

Adding some code to check if fscanf() is successful will make your code better.

Comments