0

The goal is to create a function that return the first n integers form rand() with each iteration of the loop having a different rand() result

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>

#define MAX 1000

// takes length and pointer to the integer
void randomNum(int l, int * num )
{
    char str[MAX];
    srand(time(0));
    sprintf(str , "%d", rand());
    char new[l];
    for(int i = 0; i< l; i++)
    {
        new[i] = str[i];
    }
    new[l] = '\0';

    printf("Size : %ld\n", strlen(str));
    printf("Original number : %s\n",str);
    printf("Final result : %s\n",new);
}


int main()
{
    int num;
    for (int j =0; j < 10; j++)
    {
        randomNum(1 , &num);
    }
    return 0; 
}

when compiling this code and running it it generates the same result 10 times, why does this happen when the function randomNum has srand in it that is supposed to make rand generate a different value each time

manuel
  • 23
  • 6
  • 1
    Read the documentation of `rand` carefully, especially regarding `srand`. – Cheatah Jan 29 '22 at 09:17
  • Unrelated?? (you can never dismiss **Undefined Behaviour** as unrelated) `char new[l]; /*...*/ new[l] = '\0';` <== **Buffer Overflow!** you may want to use `char new[l + 1];` instead. – pmg Jan 29 '22 at 09:23
  • Put `srand(time(0));` first in `main` and never call it again. If you seed the random number generator with the same value every time before calling `rand` you _will_ get the same result every time you call `rand`. – Ted Lyngmo Jan 29 '22 at 09:36
  • @pmg did notice that mistake but this is not related to why i keep on getting same number – manuel Jan 29 '22 at 10:02
  • @TedLyngmo can you explain why having `srand` in that function does output the same number when `time(0)` keeps on changing – manuel Jan 29 '22 at 10:05
  • @manuel It doesn't. If `time(0)` is different every time, the following call to `rand()` will also be different every time. – Ted Lyngmo Jan 29 '22 at 10:13
  • @TedLyngmo if i understand correctly `time(0)` is always constant no matter where i call it in the program – manuel Jan 29 '22 at 10:35
  • @manuel No, it'll usually return the current time in whole seconds since the epoch. That is, seconds since 1970-01-01 00:00:00. Your loop with very likely be done within one second and `time(0)` will return the same number. You may get lucky and `time(0)` may return 2 different values in such a fast loop and then you'll see two different values from `rand()` – Ted Lyngmo Jan 29 '22 at 10:37
  • 1
    @TedLyngmo makes sense don't know why i haven't thought of that – manuel Jan 29 '22 at 17:35

0 Answers0