Finish the Records Manager: the delete Command

Medium

You are given the records manager complete except for one function, and it is the one that undoes an add. Everything else is finished and correct: the growing store in growRecords, the three validation tests in addRecord, findRecord, listRecords, printStats, freeRecords, and the fgets and sscanf command loop in main. main already calls deleteRecord(struct records *db, int roll) and expects 1 when a record was removed and 0 when no record carries that roll; on 1 it prints deleted followed by the roll on standard output, and on 0 it reports the miss on standard error and prints nothing. What you write is the body of deleteRecord, which the template stubs out so the program still compiles warning-free and still runs with defined behaviour without it, reporting delete: not implemented on standard error and failing only the cases that delete something. Three steps. First, call findRecord(db, roll), which hands back a pointer to the element itself rather than a copy of it, and return 0 immediately when it is NULL, since main is the one that reports the miss. Second, turn that pointer into an index by subtracting the start of the array: index = (int)(found - db->items). Third, close the gap by copying every record after index one place to the left, walking forwards from index and copying db->items[i + 1] into db->items[i], then subtract one from db->count. This deletion keeps the records in the order they were added, so the gap is closed by shifting rather than by moving the last record into it. Two things about that loop decide whether it is right. Its bound must stop the last copy at the final record, so the loop runs while i is less than count - 1 and does not run at all when the record you deleted was already the last one. And the decrement comes after the shifting, because the loop needs the old count to know where the records end. Nothing else in the file needs changing, deletion does not shrink the array and must not call realloc, and no diagnostic wording is checked because every complaint in this program goes to standard error while the checker compares standard output only.

Success Criteria

Your code must pass 11 test case(s) to complete this exercise. 3 hint(s) are available if you need help.

How did you find this exercise?

Your rating helps us improve the content.

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.

This platform is built by its community

Every lesson, project, and tool on HelloC++ is funded by sponsors. Join them and help shape what we build next.

Become a Patron