0

I'm trying to sort a struct of data by team (data[i].team) but can't get it to work. I think I can use qsort but I can't really tell. If anyone will be able to help me ou

My struct :

struct store_race_data {
        char race_name[MAX_LENGTH];
        char first_name[MAX_LENGTH];
        char last_name[MAX_LENGTH];
        int age;
        char team[MAX_LENGTH];
        char nation[MAX_LENGTH];
        char placement[MAX_LENGTH];
        char race_time[MAX_LENGTH];
        int point;
};
typedef struct store_race_data store_race_data;

My function. (Takes all cyclists from a total list and puts them in a new struct list that matches the strcmp)

void find_all_danes(store_race_data cyclist[], int n){
        store_race_data *danes[MAX_LENGTH];
        int i, k;

        for (i=0; i<n-1; ++i) {
                if ((strcmp(cyclist[i].nation, "DEN") == 0)) {
                        danes[k] = &cyclist[i];
                        ++k;
                }
        }

        printf("\n\t\t###### BEFORE SORTING ######\n");
        print_cyclist_all_ptr(danes, k);
        printf("\n\t\t###### AFTER SORTING ######\n");
        qsort(*danes, k, sizeof(danes), &cmp_teams);
        print_cyclist_all_ptr(danes, k);

}

My compare function

int cmp_teams(const void *a, const void *b){
        const store_race_data *p1 = (store_race_data *) a,
                        *p2 = (store_race_data *) b;

        return strcmp(p1->first_name, p2->first_name);
}
Ali Öztürk
  • 113
  • 2
  • 9
  • You are missing one level of indirection. (if you want to sort the pointer array) – wildplasser Nov 25 '17 at 16:33
  • You are sorting an array of pointers. Your comparator is passed two pointers to pointers. You need to use `const store_race_data *p1 = *(store_race_data **)a;` inside the comparator. For debugging, add printing to the comparator. You'll see junk (or crashes) at the moment. With the fix, you see meaningful data. (If you use `qsort()` to sort an array of `int`, your comparator is passed two `int *` values disguised as `void *`; similarly when you sort an array of `struct store_race_data *`, your comparator is passed two `struct store_race_data **` values disguised as `void *`.) – Jonathan Leffler Nov 25 '17 at 16:34
  • @JonathanLeffler thanks for the quick answer. I still having issues understanding how to make it work properly. I can't seem to make it print the sorted list even after changing the compare function as u mentioned. . – Ali Öztürk Nov 25 '17 at 16:46
  • One of the perils of `void` pointers is that it’s hard to spot misuses. However, I do believe you didn’t add any printing to the comparator like I suggested. You should be passing just `Danes` and not `*danes`. I meant to mention that originally but forgot to add it — sorry! Also, you have the wrong sizes, I think. You should be using `sizeof(danes[0])`, which is the same as `sizeof(struct store_race_data *)`. – Jonathan Leffler Nov 25 '17 at 19:08

0 Answers0