jeudi 28 avril 2016

Why am I getting the same number for each iteration when using rand?

This is my code, it's a function which receives a matrix and the dimension of the matrix:

int** define(int **m, int n) {
    int i, j;

    srand(time(NULL));

    m = calloc(n, sizeof(int *));

    for (i = 0; i < n; i++)
        m[i] = calloc(n, sizeof(int));

    for (i = 0; i < n; i++) {
        for (j = 0; j < n; j++)
            m[i][j] = rand() % 10;
    }

    return m;
}

I want that every element of the array is a random number (independently), but when I run my program and see the matrix, it's either full of 0's, full of 1's ... or full of 9's, so all the elements of my matrix end up with the same random number... Ex:

First time I run my program:

7 7 7 7 7 
7 7 7 7 7 
7 7 7 7 7 
7 7 7 7 7 
7 7 7 7 7 

Second time I run my program:

0 0 0 0 0 
0 0 0 0 0 
0 0 0 0 0 
0 0 0 0 0 
0 0 0 0 0

It's strange because when I didn't use a function and had that piece of code inside main, it worked perfectly (each element had random numbers independently), but when I tried to do it with another function, it started to work wrong (all the element's have the same random number)




Aucun commentaire:

Enregistrer un commentaire