Read a two-dimensional array (matrix) using scanf

1

I've tried the following code:

scanf("%d %d",&N,&M);

int matrix[N][M];

for(int i=0;i<N;i++){
    for(int j=0;j<M;M++){
        scanf("%d",&matrix[i][j]);
    }
}

but when executing it does not stop asking for data, the program does not advance.

    
asked by Cristofer Fuentes 24.09.2016 в 21:59
source

1 answer

2

In not all versions of C you can assign the space to the matrix in that way, to do it dynamically you must use malloc :

int* matrix; 
int n,m;
scanf("%d", &n);
scanf("%d", &m);
matrix = malloc(n * m * sizeof(int));

Also in your code in the internal for the increment step you are doing with M ++, and consequently, it never meets the cut condition, and it remains cycling there. You should replace it with j ++

for(int i=0;i<n;i++){
    for(int j=0;j<m;j++){
        scanf("%d",&matrix[i][j]);
    }
}
    
answered by 24.09.2016 / 22:54
source