I want to create 2 matrices and fill them with reandom numbers 0-9. I just don't understand why my function doesn`t work like this. If I define a and b with e.g. #define a = 3 it works. So the problem occurs at:
void fillM(int array[a][b])
and
void printM(int array[a][b])
Original code
#include <stdio.h> #include <float.h> #include <stdbool.h> #include <stdlib.h> #include <time.h> //fill random void fillM(int array[a][b]) { for (int x=0; x < a; x++) { for (int y=0; y < b; y++) { array[x][y] = rand()%10; } } } //print void printM(int array[a][b]){ for (int x=0; x < a; x++){ for (int y=0; y < b; y++) { printf("%d ", array[a][b]); } printf("\n"); } } int Main(){ //do I really need this? srand (time(NULL)); //set size int n; printf("please set size of n x n Matrix: \n"); scanf("%d", &n); int m = n; //initialise int m1[n][m]; int m2[n][m]; fillM (m1); fillM (m2); return 0; } Revised code
#include <float.h> #include <stdbool.h> #include <stdlib.h> #include <time.h> #include <stdio.h> //fill random void fillM(size_t a, size_t b, int array[a][b]) { for (int x=0; x < a; x++) { for (int y=0; y < b; y++) { array[x][y] = rand()%10; } } } //print void printM(size_t a, size_t b, int array[a][b]){ for (int x=0; x < a; x++){ for (int y=0; y < b; y++) { printf("%d ", array[a][b]); } printf("\n"); } printf("\n"); } int main(){ srand (time(NULL)); //set size int n; printf("please set size of n x n Matrix: \n"); scanf("%d", &n); printf("\n"); int m = n; //initialise int m1[n][m]; int m2[n][m]; fillM (n, m, m1); fillM (n, m, m2); printM (n, m, m1); printM (n, m, m2); return 0; } But one more question. If I run the program now, it doesn´t fill the matrix with random numbers everywhere. It puts the same random number in every place. Do you know how to fix this?
srand (time(NULL));?" While developing it's better to comment it out so that you get a repeatable sequence. Finally, randomize the PRNG to obtain a different sequence on each run.array[x][y].