I'm coding a program in C that should rank countries by its gold medals in the olympic games.
Here's the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct _Table {
char *country;
int amnt, gold, silver, bronze;
} Table;
char *arrayAlloc(int size) {
char *array;
array = (char *) malloc(sizeof(char) * size);
return array;
}
void readTable(Table *ptr) {
char buffer[100], *cpyPtr, *savePtr;
for (int i = 0; i < ptr->amnt; ++i) {
fgets(buffer, sizeof(buffer), stdin);
buffer[strlen(buffer) - 1] = '\0';
ptr[i].country = strtok_r(buffer, " ", &savePtr);
ptr[i].country = strdup(ptr[i].country);
cpyPtr = strtok_r(NULL, " ", &savePtr);
ptr[i].gold = strtol(cpyPtr, &cpyPtr, 10);
cpyPtr = strtok_r(NULL, " ", &savePtr);
ptr[i].silver = strtol(cpyPtr, &cpyPtr, 10);
cpyPtr = strtok_r(NULL, " ", &savePtr);
ptr[i].bronze = strtol(cpyPtr, &cpyPtr, 10);
}
}
void printTable(Table *ptr) {
for (int i = 0; i < ptr->amnt; ++i) {
printf("%s %d %d %d\n", ptr[i].country, ptr[i].gold,ptr[i].silver, ptr[i].bronze);
}
}
int compare(const void *p, const void *q) {
int l = ((Table *)p)->gold;
int r = ((Table *)q)->gold;
return (r - l);
}
int main(int argc, char const *argv[]) {
int N; // Amount of lines
scanf("%d", &N);
getchar();
Table tab[N];
tab->amnt = N;
tab->country = arrayAlloc(100);
readTable(tab);
qsort(&tab->gold, tab->amnt, sizeof(Table), compare);
printTable(tab);
free(tab->country);
return 0;
}
Input example:
4
BRA 3 4 5
USA 23 76 34
CHN 23 54 12
GER 10 20 23
Expected output:
USA 23 76 34
CHN 23 54 12
GER 10 20 23
BRA 3 4 5
What I'm getting:
BRA 23 54 12
GER 23 76 34
CHN 3 4 5
USA 10 20 23
As you can see it seems to "sort" it somehow. However it is far from what I need to accomplish. I've already tried to modify the compare() function, but without success. What am I possibly missing here?
tabis an array. It's this array you should sort, not the first elementsgoldmember. The expressiontab->goldis equal totab[0].gold.