0

I was doing something when learning and i have encountered the next problem. To simplify and to shorten the question i reduced the code exactly to the problem.

I want to read a matrix and just output it on my screen. But when i run this piece of code:

int main(){
    int in, jn, row, col, **mat;
    scanf("%d %d", &row, &col);
    mat = (int **) malloc(row * col * sizeof(int *));
    for(in = 0; in < col; in++){
        mat[in] = (int *) malloc((col + 1) * sizeof(int));
    }
    if(mat == NULL){
        printf("Error. Allocation was unsuccessful. \n");
        return 1;
    }
    for(in = 0; in < row; in++){
        for(jn = 0; jn < col; jn++){
            scanf("%d", &mat[in][jn]);
        }
    }
    for(in = 0; in < row; in++){
        for(jn = 0; jn < col; jn++){
            printf("%d ", mat[in][jn]);
        }
        printf("\n");
    }
    return 0;
}

i get segmentation fault. I debugged the program and the error appears when in = 2 and jn = 0. So i read: 1 2 3 4 and here i get the segmentation fault, when trying to read into mat[2][0]. And i do not understand why. The error

And i have another version of this here:

int main(){
    int in, jn, row, col;
    scanf("%d %d", &row, &col);
    int mat[row][col];
    for(in = 0; in < row; in++){
        for(jn = 0; jn < col; jn++){
            scanf("%d", &mat[in][jn]);
        }
    }
    for(in = 0; in < row; in++){
        for(jn = 0; jn < col; jn++){
            printf("%d ", mat[in][jn]);
        }
        printf("\n");
    }
    return 0;
}

The problem with this one is that i can`t see the the values in watches in codeblocks. For mat[0][0](by example) instead of the first element of the matrix i see this "Cannot perform pointer math on incomplete types, try casting to a known type, or void *."

For me this is a strange behavior and i do not understand it. Why do i get segmentation fault in the first version and why can`t i see the matrix in watches window?

Timʘtei
  • 753
  • 1
  • 8
  • 21

1 Answers1

1

The amount of memory allocation of type (*int) was off. All you need is the number of rows. For each row, all need is number of columns of type (int). Here is a link to difference between array and pointer. link

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

 int main(){
    int in, jn, row, col, **mat;
    scanf("%d %d", &row, &col);
    mat = malloc(row * sizeof(int *));
    if(mat == NULL){
       printf("Error. Allocation was unsuccessful. \n");
       return 1;
     }
     for(in = 0; in < row; in++){
        mat[in] = malloc(col * sizeof(int));
        assert(mat[in]!=NULL);
     }
     for(in = 0; in < row; in++){
       for(jn = 0; jn < col; jn++){
          scanf("%d", &mat[in][jn]);
       }
     }
     for(in = 0; in < row; in++){
        for(jn = 0; jn < col; jn++){
           printf("%d ", mat[in][jn]);
        }
        printf("\n");
     }
    return 0;
 }
Nguai al
  • 958
  • 5
  • 15