I am currently learning C and I need to write a function to create an array of random integers. I've hit a problem where after creating I try to print and it the first 8 numbers correctly but the rest don't.
int* create(int n) {
int* array = malloc(n);
if (!array) return NULL;
srand(time(NULL));
for (int i = 0; i < n; i++) {
array[i] = rand() % 100 + 1;
printf("num: %i\n", array[i]);
}
for (int i = 0; i < n; i++) {
printf("%i\n", array[i]);
}
return array;
}
Here is my output for this:
num: 39
num: 2
num: 15
num: 74
num: 80
num: 29
num: 14
num: 16
num: 8
num: 11
num: 2
39
2
15
74
80
29
14
16
973747761
909588276
2614
Issues with your code:
malloc
expects a size_t
, you are directly giving an int
. So you should technically do:
int *array = malloc(sizeof(int) * n);
This basically says that allocate n
blocks of sizeof(int)
bytes each.
What you are doing is allocating n
bytes of data. The program is not guaranteed to run always and you are running out of bounds. If you were lucky you would get a Segmentation Fault
in one of the runs.