Lab 7: Dynamic Memory
Due by the end of class
Introduction
This week you will be dealing with dynamic memory allocation.
Lab Exercise
For this lab you may use the readInt()
function from earlier labs or employ the scanf()
function you just learned. Either one can
read in integers from the command prompt. You will be reading in two sorted arrays. The very first
integer you read in will be the length of the first list. Let's call it length1
. The second integer will
be the length of the second list. Let's call it length2
. The next length1
integers will be the values in the
first list and the following length2
integers will be the values in the second list. You can assume that
the two lists are both sorted. You will need to store these sorted lists in integer arrays, and then
allocate an integer array with length length1 + length2
to store the merged result.
Write a merge()
function with the following prototype.
void merge(int array1[], int length1, int array2[], int length2, int result[]);
Note that merge()
takes the result
array as the last parameter. This array is where the merged arrays should be stored.
You'll notice that in the requirements above, nothing was mentioned about a maximum input size for the two lists.
Therefore, you cannot assume a maximum line length. What a difficulty! If you don't know
how many integers could be stored, how can you allocate an integer array big enough to hold it?
Unsurprisingly, you must dynamically allocate all three arrays using malloc()
.
Your program will read each integer on a different line. After reading in both lists, your program should print out
each list separately followed by the merged list. To print out a list you can simply separate each element
with a space. A sample execution follows. User input is in green
.
5 2 3 8 12 19 34 20 22 List 1: 3 8 12 19 34 List 2: 20 22 Merged list: 3 8 12 19 20 22 34
Note: It is possible to print out the merged list without storing it into a third array. Please do not do so. In other words, copy the values into the third array in order even though it is not strictly necessary.
Use free()
to free the memory used for each array before your program ends.
Turn In
Zip the contents of your lab directory, including the makefile and the source C file. Upload this zip file to Brightspace. Do not include any object files or executables. Running the make
command must compile the required C source code file and generate an executable named merge
.
All work must be done individually. Never look at someone else's code. Please refer to the course policies if you have any questions about academic integrity. If you have trouble with the assignment, I am always available for assistance.