Reputation: 115
I need to store random numbers between 500 and 600 to an array using a pointer and then print out those numbers. I get a segmentation error...core dump, I don't really understand what that means. The error happens after the printf statement ("%15d\n", aPtr[i]);
int main(){
int size;
int j, i;
int temp;
int sum = 0;
printf("Enter size of array");
scanf("%d", &size);
int array[size];
int *aPtr = malloc(sizeof(int) * size);
for (i = 0; i <= size; i++){
srand(time(NULL));
aPtr[i] = rand() % 500 + 100;
printf("%15d\n", aPtr[i]);
Upvotes: 0
Views: 20039
Reputation: 881093
You need to call srand
before you enter the loop.
As it stands now, you'll get a long sequence of identical numbers because you're resetting the random number generator to the same seed each time (assuming the time doesn't change, which is likely). In addition, if you want numbers between 500 and 600 inclusive, your formula is wrong. Try this snippet:
srand(time(NULL));
for (i = 0; i < size; i++){
aPtr[i] = (rand() % 101) + 500;
printf("%d\n", aPtr[i]);
}
Upvotes: 1
Reputation: 749
you need to call srand ( which initializes the random number generator ) only once. Move it out of the for. And if you want random numbers between 500 and 600, you need to generate them between 0 and and 100 ( rand() % 101) and then add 500.
Upvotes: 1
Reputation: 15916
i <= size;
should be i < size;
If you have an array of 50 items, the valid indices are [0,49].
Upvotes: 4