Allocating an array of integers
Let's quickly visit another example of malloc().
We'll allocate enough memory to hold an array of integers:
#include <stdlib.h>
int *randomints(int wanted)
{
int *array = malloc( wanted * sizeof(int) );
if(array != NULL) {
for(int i=0 ; i<wanted ; ++i) {
array[i] = rand() % 100;
}
}
return array;
}
|
Of note:
- malloc() is used here to allocate memory that we'll be treating
as integers.
- malloc() does not know about our eventual use for the memory it
returns.
- how much memory did we need?
We know how many integers we want, wanted,
and we know the space occupied by each of them, sizeof(int).
We thus just multiply these two to determine how many bytes we ask
malloc() for.
CITS2002 Systems Programming, Lecture 12, p7, 28th August 2024.
|