3
In another of my studies in the C language, I had the idea of trying to fill a dynamically allocated vector with random numbers. However, I came across the following problem: The Rand function was set to randomize a number every second. As the filling speed is too fast, the "for" ends up filling this vector in less than a second, and therefore, all inserted values are exactly equal.
My knowledge in the area is still quite limited, so at the moment I could not find any solution to this. What I know is that I could take srand out of my code. But it would generate the same numbers every time I restart its execution.
Would anyone have an idea? And if you did, could you explain it to me? I’m a beginner. So it’s important that I understand the process.
Thanks in advance!
#include "stdio.h"
#include "stdlib.h"
#include "time.h"
int main()
{
int k = NULL, *matriz = NULL;
printf("Tamanho do vetor: ");
scanf("%i", &k);
matriz = (int *)malloc(k * sizeof(int));
for (int i = 0; i < k; i++)
{
srand(time(NULL));
matriz[i] = rand() % k + 1;
printf("Valor %i : %i" , i+1, matriz[i]);
printf("\n");
}
system("pause");
return 0;
}
Wow, thanks Omni! This really solved the problem and got much better and faster than the conditions I had entered. After all, he explained it well! Thanks!
– Aesthesys