Search code examples
cmultidimensional-arrayscanfpass-by-pointer

Using scanf() with a pointer to a double pointer


I feel like I've attempted every combination I know of to get this to work and can't figure it out. How can I scanf() into an int** passed as a pointer to a function? I tried searching but couldn't find this, if it's a duplicate please let me know and I'll delete. It begins to run and after entering a few values it segfaults.

Here's my code, I think it's messing up on the scanf() line of the setMatrix() function:

#include <stdio.h>
#include <stdlib.h>

// create zero initialized matrix
int** callocMatrix(int rmax, int colmax) {  
        int **mat = calloc(rmax, sizeof(int*));
        for(int i = 0; i < rmax; i++) mat[i] = calloc(colmax, sizeof(int));
        return mat;
}

// fill matrix
void setMatrix(int ***mat, int r, int c){
    printf("Insert the elements of your matrix:\n");
    for (int i = 0; i < r; i++) {
        for (int j = 0; j < c; j++) {
            printf("Insert element [%d][%d]: ", i, j);
            scanf("%d", mat[i][j]); // problem here??
            printf("matrix[%d][%d]: %d\n", i, j, (*mat)[i][j]);
        }
    }   
    return;
}

// print matrix
void printMatrix(int ***mat, int r, int c){ 

    for (int i=0; i<r;i++){
        for (int j=0; j<c;j++) {
                printf("%d ", (*mat)[i][j]);
        }
        printf("\n");
    }

}

int main(int argc, char *argv[]) {

    int r = 3, c = 3;

    int **mat = callocMatrix(r, c);

    setMatrix(&mat, r, c);

    printMatrix(&mat, r, c);
}

Solution

  • There is no need to use triple pointer ***. Passing two-dimensional array will work as is. Here is the code:

    #include <stdio.h>
    #include <stdlib.h>
    
    // create zero initialized matrix
    int** callocMatrix(int rmax, int colmax) {
        int **mat = calloc(rmax, sizeof(int*));
        for(int i = 0; i < rmax; i++) mat[i] = calloc(colmax, sizeof(int));
        return mat;
    }
    
    // fill matrix
    void setMatrix(int **mat, int r, int c){
        printf("Insert the elements of your matrix:\n");
        for (int i = 0; i < r; i++) {
            for (int j = 0; j < c; j++) {
                printf("Insert element [%d][%d]: ", i, j);
                scanf("%d", &mat[i][j]); // no problem here
                printf("matrix[%d][%d]: %d\n", i, j, mat[i][j]);
            }
        }
    }
    
    // print matrix
    void printMatrix(int **mat, int r, int c){
    
        for (int i=0; i<r;i++){
            for (int j=0; j<c;j++) {
                    printf("%d ", mat[i][j]);
            }
            printf("\n");
        }
    }
    
    int main(int argc, char *argv[]) {
    
        int r = 3, c = 3;
    
        int **mat = callocMatrix(r, c);
    
        setMatrix(mat, r, c);
    
        printMatrix(mat, r, c);
    }