I'd like to fill and print a static matrix, for sorting then with the Young Tablue proprieties Here, but I have a problem with some dimension (row and col) input, with some input show me the right matrix, but with others give me seg.fault or a weird output. Here the function:
#include <stdio.h>
#include <stdlib.h>
#define MAX 32
void fill( int A[MAX][MAX], int numRig, int numCol, int numElem){
int i,j;
int count = 0;
for ( i = 0 ; i < numRig; i++ ) {
for ( j = 0 ; j < numCol; j++) {
A[i][j] = rand() % 20;
//fscanf(stdin,"%d", &A[i][j]);
//DEBUG
printf("%d\n", A[i][j]);
}
}
}
void stamp(int A[MAX][MAX], int numRig, int numCol){
int k,h;
for ( h = 0 ; h < numRig; h++ ) {
for ( k = 0 ; k < numCol; k++) {
printf("%d ", A[h][k]);
}
printf("\n");
}
}
the main
int main () {
int row,col;
printf("Insert row and col:\n");
scanf("%d %d", &row, &col);
int A[row][col];
fill(A,row,col);
stamp(A,row,col);
return 0;
}
output with row=4 and col=4: "3 6 17 15 -1 0 0 0 2017675728 32765 -741456064 21906 -1 0 0 0 2017675728 32765 -741456064 21906 0 0 -741454033 21906 2017675728 32765 -741456064 21906 0 0 -741454033 21906 4 0 0 0 0 0 -741454033 21906 4 0 0 0 2017675976 32765 2017675552 32765 4 0 0 0 2017675976 32765 2017675552 32765 3 0 0 0 2017675976 32765 2017675552 32765 3 0 0 0 4 0 0 0 "
I tried with dynamic allocation:
a=(int**)malloc(row*(sizeof(int*)));
for(i=0;i<row;i++)
a[i]=(int*)malloc(col*sizeof(int));
and all works fine, but I must use static allocation.