Structure Exercise
Objective
To get practice writing C programs, including structs.Task
For this lab, you will create a simple structure and a few functions to operate on it. The structure will represent a high score in a video game and will contain two fields:
- The name of the player which can be three characters long (not including the NULL terminator).
- The score which is an integer.
You should write three functions which work on these structures:
- score_set - this takes a pointer to a score, a string and an integer. It should check that the string is three characters or less, and that the integer is non-negative. If either constraint is violated this function should return 0. If the data is OK, it should store those values in the score object passed in, and return 1.
- score_print - this function should take a pointer to a score structure and print it to the screen. It should print the name, then a space, and then the score value.
- score_compare - this function should take two pointers to structures. It should compare their score values. If the first one is less, it should return 1. If the second one is less, it should return -1. If they are equal, it should return 0.
Sample Run
You should test your structure and functions with the following main function:
#include <stdlib.h>
int main() {
/* create an array of scores */
Score scores[10];
/* put in some test data */
score_set(&scores[0], "IAN", 750);
score_set(&scores[1], "BOB", 1200);
score_set(&scores[2], "ADA", 3500);
score_set(&scores[3], "SUE", 900);
score_set(&scores[4], "EVA", 500);
score_set(&scores[5], "BEN", 1500);
score_set(&scores[6], "ROY", 3000);
score_set(&scores[7], "KIM", 1250);
score_set(&scores[8], "VIC", 2500);
score_set(&scores[9], "DAN", 1800);
/* sort them using the compare function above */
qsort(scores, 10, sizeof(Score),
(int (*) (const void*, const void*)) &score_compare);
/* display them */
for (int i = 0; i < 10; i++) {
score_print(&scores[i]);
}
return 0;
}
This program would output the following:
ADA 3500 ROY 3000 VIC 2500 DAN 1800 BEN 1500 KIM 1250 BOB 1200 SUE 900 IAN 750 EVA 500
Submitting
When you are done, please submit the C code under the assignment in Canvas.