Pergunta

Below but it always gives me 42 as SIZE. I wanted to randomise SIZE with srand(time(NULL)) but obviously it is not working because it is below randomisation of SIZE. When I try to add it before randomization of SIZE, compiler yells at me. Do you have any ideas how to correct it?

int i,numberToBeFound;
int SIZE=(rand()%100)+1; // size can be in the range [1 to 100]
int *array2 = (int*) malloc(sizeof(int)*SIZE);

srand(time(NULL));

for(i=0;i<SIZE;i++)     //fill the array with random numbers
    array2[i]=rand()%100; 
Foi útil?

Solução 2

You need to call srand() before you call rand() to initialize the random number generator.

You can try srand( time( NULL ) ) which will give you a different result once per second. If you need it to be more variable than that, then you will have to come up with a better way to seed the number generator.

int i,numberToBeFound;
int SIZE;
int *array2;

srand( time( NULL ) );

SIZE=(rand()%100)+1; // size can be in the range [1 to 100]
array2 = malloc(sizeof(int)*SIZE);

for(i=0;i<SIZE;i++)     //fill the array with random numbers
    array2[i]=rand()%100; 

PS: You should not cast malloc() in C -- see this post.

Outras dicas

int i, numberToBeFound;
int SIZE=0;
int* array2=0;

srand(time(NULL));

SIZE=(rand()%100)+1; // size can be in the range [1 to 100]
array2 = (int*) malloc(sizeof(int)*SIZE);

for(i=0;i<SIZE;i++)     //fill the array with random numbers
    array2[i]=rand()%100;

It is ancient C (C89 or older). So declare your locals, then init them, and finally use them as needed.

You say in a comment that if you call srand() before rand(), your compiler doesn't accept it.

That's because your compiler (Microsoft?) is enforcing C89/C90 rules, which don't permit declarations to follow statements within a block.

You can work around that limitation by adding a new block. A rough outline:

srand(time(NULL));
{
     int size = rand() % 100 + 1;
     /* ... */
}

Or you can remove the initializers for size and array2, replacing them with assignments after calling srand(). Personally, I prefer to initialize variables as early as possible.

Generally speaking, you should call srand() exactly once in your program, before any calls to rand(). (That's for the most general case where you want non-repeating pseudo-random numbers; if you actually need a repeatable sequence, a different strategy is appropriate.)

(Without a call to srand(), rand() behaves as if you had called srand(1), and generates the same sequence each time.)

(I've changed the name of your variable SIZE to size; all-caps identifiers are conventionally used for macros.)

To not get always the same result from rand you need to seed the generator with srand before doing any calls to rand. So you only need to move your srand call to a place before calling rand.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top