Reputation: 73
I am taking in an input from a text file that looks something like this:
3
2
4
1 2
3 4
5 6
7 8 9 10
11 12 13 14
With the first line being the number of rows in matrix A stored in m, 2nd row being the number of columns in matrix A and number of rows in Matrix B stored in n, and 3rd row being the number of columns in matrix B stored in p.
I am grabbing the information from the text file using this function:
void read_matrices(int **A, int **B, int **C, int *m, int *n, int *p, char *file) {
FILE *fp = fopen(file, "r");
if (!fp) {
fprintf(stderr, "\n Error: file open failed for file '%s'\n\n", file);
exit(0);
}
/* read & output m, n, p */
fscanf(fp, "%d\n%d\n%d\n", m, n, p);
/* allocate memory for A and set values to null */
*A = (int*)calloc(*m * *n, sizeof(int));
/* read A */
int i, j;
for (i = 0; i < *m; i++) {
fscanf(fp, "\n");
for (j = 0; j < *n; j++) {
fscanf(fp, "%d", (A + i * *n + j));
}
}
/* allocate memory for B and set values null */
*B = (int*)calloc(*n * *p, sizeof(int));
/* read B */
for (i = 0; i < *n; i++) {
fscanf(fp, "\n");
for (j = 0; j < *p; j++) {
fscanf(fp, "%d", (B + i * *p + j));
}
}
/* allocate memory for C and set values null */
*C = (int*)calloc(*m * *p, sizeof(int));
/* close FP & free allocated memory */
fclose(fp);
}
I am printing the matrix using the function:
void print_matrix(int *mtx, int r, int c) {
int i, j;
for (i = 0; i < r; i++) {
printf("\n");
for (j = 0; j < c; j++) {
printf("%5d", (mtx + i * c + j));
}
}
}
When I print out the matrix's I am getting the wrong numbers out. But when I try printing inside the read function I get the correct result. I am getting the result:
Matrix A contents:
8 12
16 20
24 28
Matrix B contents:
7 11 15 19
23 27 31 35
Also when I change fscanf(fp, "%d", (A + i * *n + j)); to fscanf(fp, "%d", *(A + i * *n + j)); I get a Bus Error, but the way I have it now I get warning: int format, pointer arg.
Upvotes: 2
Views: 363
Reputation: 66194
Both your targets for writes in your element-reads are using the wrong pointer values.
fscanf(fp, "%d", (A + i * *n + j));
should be
fscanf(fp, "%d", (*A + i * *n + j));
// here ----------^
Similar problem with the second matrix:
fscanf(fp, "%d", (B + i * *p + j));
should be
fscanf(fp, "%d", (*B + i * *p + j));
// here ----------^
Most modern compilers will warn you about this, and if you're doesn't either jack up the compiler warnings or get a toolchain with brains. clang, for example, emits:
main.c:24:30: Format specifies type 'int *' but the argument has type 'int **'
Upvotes: 1