An Array Whose Size Arrives at Run Time
MediumWrite the program lesson 1 could not: the first number on standard input says how many numbers follow, and there is no capacity written anywhere in the source. Read that count, allocate exactly that many ints on the heap, read the numbers into the block, then print three lines: sum: followed by the total, average: followed by the mean to one decimal place with %.1f, and reversed: followed by the numbers from last to first, each preceded by a single space so the line has no trailing space. Then free the block. Three TODOs mark the work and the surrounding program is already written. TODO 1 is the allocation, and both of the lesson's rules are being checked: size the request from the object with count * sizeof *values rather than from the type, and do not cast the result, because malloc returns void * and C converts it for you. The NULL check below it is already in place and must stay, since checking every allocation before using the block is not optional in this course; the graders cannot make an allocation fail, so the branch is there to be correct rather than to be exercised. TODO 2 is the fill, one scanf per element into values[i] with its return value tested, adding each number to total as it arrives. Remember that malloc does not initialize, so every element you are going to read must first be written; that is why the failure branch matters. If scanf converts nothing, print expected followed by the count and the word numbers, free the block, and return 0, because a path that returns without freeing is a leak and this exercise fails on leaks. TODO 3 is the free on the success path, and the whole exercise turns on there being exactly one free per allocation on every route through the program: free it twice and AddressSanitizer reports attempting double-free, print anything after freeing it and you have a use-after-free. The count guard at the top is written for you and handles a count of zero, a negative count, and input that is not a number at all, each of which prints expected a positive count and returns before anything is allocated. Every path returns 0, since a nonzero exit status is a failure however correct the printed output looks.
Success Criteria
Your code must pass 7 test case(s) to complete this exercise. 3 hint(s) are available if you need help.
Sign in to track your progress
You can work on exercises as a guest, but sign in to track your progress and save your submissions.