0

Setting matrices with rand() function

Hi everyone! I wrote a function that is supposed to assign values to each element of a matrix using the rand function, but when I set two matrices, their elements are always the same. Can you please help? --------------------------------- //language: C #include <stdio.h> #include <stdlib.h> #include <time.h> void set_matrix(int *M, int row, int col){ srand(time(0)); int i, j; for(i = 0 ; i < row ; i++){ for(j = 0 ; j < col ; j++){ *(M+i*col+j) = rand() % 9 + 1; } } } void print_matrix(int *M, int row, int col){ int i, j; for(i = 0 ; i < row ; i++){ for(j = 0 ; j < col ; j++){ printf("%d ", *(M+i*col+j)); } printf("\n"); } } int main() { int A[2][3], B[2][3]; set_matrix(&A[0][0], 2, 3); set_matrix(&B[0][0], 2, 3); printf("A:\n\n"); print_matrix(&A[0][0], 2, 3); printf("\nB:\n\n"); print_matrix(&B[0][0], 2, 3); return 0; }

12th May 2020, 4:29 PM
H2727
H2727 - avatar
4 Respostas
0
Why did you pass zero to time?
12th May 2020, 11:37 PM
Mark McGuire
Mark McGuire - avatar
0
Isn't that what I'm supposed to do?
13th May 2020, 5:17 AM
H2727
H2727 - avatar
0
It appears to want NULL.
13th May 2020, 1:04 PM
Mark McGuire
Mark McGuire - avatar
0
I guess zero is standard procedure with srand (time ())
13th May 2020, 1:08 PM
Mark McGuire
Mark McGuire - avatar