a. Create an integer array of size 10 using malloc and populate it with random numbers
between 500 & 1000.
b. Create another integer array of size 20 using calloc and populate it with random
numbers between 1000 & 2000..
I've gotten it to work, but about 1 out of any 3 times the program crashes. Is there any way to fix this?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
main()
{
srand((unsigned)time(NULL));
int *numbers;
int *numbers2;
int *combine;
numbers =(int *) malloc(10*sizeof(int));
numbers2 = (int*) calloc(20,sizeof(int));
printf("Here is the list of numbers made with malloc!\n\n");
for(int x=0; x<10; x++)
{
numbers[x]=(rand()%500)+501;
printf(" Malloc Number #%d: %d\n", x+1, numbers[x]);
}
printf("\n\n");
printf("Here is the list of numbers made with calloc!\n\n");
for(int y=0; y<20; y++)
{
numbers[y]=(rand()%1000)+1001;
printf(" Calloc Number #%d: %d\n", y+1, numbers[y]);
}
printf("\n\n");
system("PAUSE");
}
In the second loop you are using array numbers but you need to use numbers2. numbers array holds only 10 integers so in the second loop you iterate out of bounds.
1 2 3 4 5
for(int y=0; y<20; y++)
{
numbers2[y]=(rand()%1000)+1001; // fixed
printf(" Calloc Number #%d: %d\n", y+1, numbers2[y]); // and here
}