Search code examples
cpointersmatrixscanfcalloc

error: invalid operands to binary * Pointer to a pointer to a matrix


I am getting error: invalid operands to binary * on lines 13, 20, 25, 31, and 36. I'm not sure how to deal with dynamic memory allocation to a pointer to a pointer to a matrix. Also, how to store integers in a matrix like fashion with this pointer to a pointer. Also, I realize there are lots easier ways of going about this in terms of the pointers, but I have to not use any brackets and the functions inputs were supplied to me.

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);
    printf("\n m: %d\n n: %d\n p: %d\n\n", *m, *n, *p);

    /* allocate memory for A and set values to null */
    A = 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 = 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 = calloc(m * p, sizeof(int));

    /* close FP & free allocated memory */
    fclose(fp);
}

Solution

  • It's a bit hard to understand what you are doing in that function, but it seems you just need to better understand pointers in C.

    For this line:

    A = calloc(m * n, sizeof(int));
    

    What this is doing is it is trying to multiply two pointers, but I'm assuming you want to multiply the values they point to, so you need to prefix m and n with a * to de-reference them (and get their value).

    For the assignment to A, what you are trying to do right now, is assign a pointer to a "pointer to a pointer", which is impossible. You need to deference A by prefixing it with a * to get the pointer that it is pointing to, and then you also should be casting the result of calloc to (int*) to match what you are assigning to.

    Example:

    *A = (int*)calloc(*m * *n, sizeof(int));
    

    The same rules apply to the other errors in the code.