Skip to content

Instantly share code, notes, and snippets.

@boki1
Last active April 29, 2019 20:53
Show Gist options
  • Save boki1/986fbc5536c752d64b5ac6a71cd290cf to your computer and use it in GitHub Desktop.
Save boki1/986fbc5536c752d64b5ac6a71cd290cf to your computer and use it in GitHub Desktop.
Student Sorting - School HW - 24/04/2019
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define stringize(s) #s
enum subjects {
maths,
history,
programming,
geography,
count
};
struct student {
int marks[count];
char name[];
};
typedef unsigned char grade;
typedef const struct student** student_doubleptr;
struct student *alloc_student(const char *name, grade _maths, grade _history, grade _programming, grade _geography) {
struct student *res = calloc(1, sizeof(struct student) + strlen(name) + sizeof "");
if (!res)
return 0;
strcpy(res->name, name);
res->marks[maths] = _maths;
res->marks[history] = _history;
res->marks[programming] = _programming;
res->marks[geography] = _geography;
return res;
}
int compare_programming(const void *p1, const void *p2) {
student_doubleptr s1 = (student_doubleptr) p1,
s2 = (student_doubleptr) p2;
if ((**s1).marks[programming] > (**s2).marks[programming])
return -1;
if ((**s1).marks[programming] < (**s2).marks[programming])
return 1;
return 0;
}
void print_index(struct student *index[], const int subject, const unsigned class_size) {
for (unsigned i = 0; i < class_size; ++i)
printf("%s has %d.\n", index[i]->name, index[i]->marks[subject]);
}
int main(int argc, const char const *argv[]) {
const unsigned CLASS_SIZE = 4;
struct student *all[] =
{
alloc_student("Georgi Ivanov", 4, 6, 2, 5),
alloc_student("Petyr Borisov", 5, 3, 4, 4),
alloc_student("Filip Kostadinov", 5, 3, 5, 4),
alloc_student("Petyo Atanasov", 2, 3, 6, 4)
};
struct student *programming_index[CLASS_SIZE];
memcpy(programming_index, all, sizeof all);
qsort(programming_index, CLASS_SIZE, sizeof *programming_index, compare_programming);
printf("sorting by %s...\n", stringize(programming));
print_index(programming_index, programming, CLASS_SIZE);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment