samedi 4 avril 2020

Filling an array with random numbers in a range in C

What I try to do is to create a function thay allocates memory for an array and fills it up with random numbers in a specified range(in my case 50-76).srandis in the main and I use the <time.h> header.

unsigned* randomgen(int size, unsigned max, unsigned min)
{
    int i;
    unsigned* arr = (unsigned*)malloc(size * sizeof(unsigned));
    for (i = 0; i < size; i++) {
        arr[i] = (rand() % (max - min + 1)) + min;
        printf("%d ", arr[i]);
    }
    return arr; 
}

I want to get numbers like 60 52 68 .... What is happening is that the numbers generated look something like3526 4582 13224 .... This is only happening in this function.When I do it in main I get the wanted results.




Aucun commentaire:

Enregistrer un commentaire