I'm trying to make a function that initializes a random 2 dimensional square matrix given its variable name and number of rows and columns (n in this case). This code returns a "Segmetation fault" error and I don't know why. I've tried using & in if-else in the function initM, but then returns "error: lvalue required as left operand of assignment"Anyone knows how to make it work?
void initM (int n, int **matrix){
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
if (i == j) matrix[i][j] = 101;
else matrix[i][j] = (rand() % 101);
}
}
}
void main (int argc, char *argv[]){
int n = atoi(argv[1]);
int **matrix = (int **)malloc(n*sizeof(int));
for(int i = 0; i < n; i++) matrix[i] = (int *)malloc(n*sizeof(int));
initM(n, matrix);
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
printf("%d ", matrix[i][j]);
}
printf("\n");
}
for (int i = 0; i < n; i++) free(matrix[i]);
free(matrix);
}
int **matrix = (int **)malloc(n*sizeof(int));-->int **matrix = malloc(n*sizeof(int *));notice size of a pointer tointand without the cast.sizeof(int)where you needsizeof(int *).""to show code AND error messages ...