In one more of my studies in Language C, I had the idea of trying to populate 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 fill speed is too fast, the "for" ends up filling that vector in less than a second, so all the values entered are exactly the same.
My knowledge in the area is still very limited, so at the moment I could not find any solution for this. What I do know is that I could get the srand out of my code. But it would generate the same numbers every time I rebooted it.
Would anyone have an idea? And if I had, could you explain it to me? I'm a beginner. So it's important that I understand the process.
Thank you 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;
}