For this assignment you will write a function which allocates an array on the heap using malloc()
or calloc()
, fills the array with random integers within a certain range, and returns a pointer to the array.
The assignment contains a Makefile
, main.c
, sequence.h
, and sequence.c
. main.c
will use the function that you write. sequence.h
contains the prototype for the function. You will implement the function in sequence.c
. There is no need to make modifications to any file except for sequence.c
.
Running make will produce the executable random_sequence
main()
The main()
function, which is already written for you, reads the command line arguments, seeds the random number generator, calls your function to get the array, prints out the values in the array, and then frees the array with free()
.
The program takes 3 command line arguments: the count of numbers in the sequence, the minimum random value in the sequence, and the maximum random value in the sequence. Here is an example run, which generates a sequence of 10 random integers between 1 and 20:
$ ./random_sequence 10 1 20
Here is the sequence:
7 20 1 19 7 9 2 3 18 13
create_random_sequence()
functionHere is the prototype for the function:
int *create_random_sequence(size_t count, int min, int max);
Implement this function in sequence.c
. Create the array on the heap using malloc()
. The array must have enough space to hold count integers.
Here is the prototype for malloc()
:
void *malloc(size_t size)
The size
is the number of bytes to allocate. Since an int
takes up more than 1 byte of space, you need to multiply count
by sizeof(int)
to get the appropriate number of bytes to pass to malloc()
.
malloc()
returns a generic void *
pointer, which you can assign to an int *
. See the code on GitHub for an example of this.
Once you have created the array, fill it by placing a random number at each index of the array. Recall that we generated a random number from 1 to 6 to roll a die like this:
rand() % 6 + 1
You will need to generalize this so that it can produce random numbers within any range.
You can run the GitHub testing locally with the command:
make gh-test-sequence
Push your submission when you are done. Tests will be run using your function. For full credit the tests must pass and you must have proper style.
Your grade for this assignment will be out out of 10 points:
create_random_sequence
function in sequence.c
according to specification