Search code examples
cpointersmultidimensional-arraymallocdynamic-memory-allocation

C-2d array print function not working when I call it in main function


I wrote two functions, readMatrix which allocate a double pointer and take the input from keyboard and the second function is a print function.

When I call the print function in main function, it does not work completely.

This is the code :

void print(int** mat, int lin, int col) {
    int i,j;
    printf("Matrix is:\n");
    for(i=0; i<lin; i++) {
        for(j=0; j<col; j++) {
            printf("%d ", *(*(mat+i)+j));
        }
        printf("\n");
    }
}

int** readMatrix(int** mat, int lin, int col) {
    int x;
    int i,j;
    mat==(int**)malloc(lin*sizeof(int*));
    for(x=0; x<lin; x++) {
        mat[x]=(int*)malloc(col*sizeof(int));
    }
    
    for(i=0; i<lin; i++) {
        printf("Line %d: ", i);
        for(j=0; j<col; j++) {
            scanf("%d",  &mat[i][j]);
        }
    }
}


int main()
{
    int lin, col;
    int i,j;
    printf("Enter number of lines: ");
    scanf("%d", &lin);
    printf("Enter number of cols: ");
    scanf("%d", &col);
    int** mat = readMatrix(mat,lin,col);
    print(mat,lin,col);
    return 0;
}

After I take the input, I get the message "Matrix is" but the matrix does not appear, why?

If I call the print function inside readMatrix function, it works, but why is not working if I call it in main?

Thanks.


Solution

  • The parameter mat is not used in the function readMatrix because its value id overwritten

    int** readMatrix(int** mat, int lin, int col) {
        int x;
        int i,j;
        mat==(int**)malloc(lin*sizeof(int*));
        //...
    

    Moreover the function returns nothing though its return type is not void.

    So this record

    int** mat = readMatrix(mat,lin,col);
    

    invokes undefined behavior.

    You need to declare the function at least lie

    int** readMatrix( int lin, int col);
    

    and at the end of the function to write

    return mat;
    

    For example

    int** readMatrix(int lin, int col) {
        int **mat==(int**)malloc(lin*sizeof(int*));
        //...
    
        return mat;
    }
    

    And the function will be called like

    int** mat = readMatrix(lin,col);
    

    Also in main you should free the all allocated memory when the arrays is not needed any more.

    For example

    for ( i = 0; i < lin; i++ )
    {
        free( mat[i] );
    }
    
    free( mat );