Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

qsort of struct array not working

I am trying to sort a struct run array called results by a char, but when I print the array, nothing is sorted. Have a look at this:

struct run {
  char name[20], weekday[4], month[10];
  (And some more...)
};
typedef struct run run;

int name_compare(const void *a, const void *b) 
{
    run *run1 = *(run **)a;
    run *run2 = *(run **)b;
    return strcmp(run1->name, run2->name);
}

int count_number_of_different_persons(run results[])
{
  int i = 0;


  qsort(results, sizeof(results) / sizeof(run), sizeof(run), name_compare);

  for(i = 0; i <= 999; i++)
  {
    printf("%s\n", results[i].name);
  }
  // not done with this function yet, just return 0
  return 0;
}

The output from the above is just a list of names in the order they were originally placed

like image 967
Andreas Strandfelt Avatar asked Jan 18 '26 09:01

Andreas Strandfelt


1 Answers

int count_number_of_different_persons(run results[])

This doesn't really let you use sizeof on the array, because array is decayed to pointer.

This

run *run1 = *(run **)a;

also looks weird, shouldn't it be

run *run1 = (run*)a;

?

like image 156
Michael Krelin - hacker Avatar answered Jan 20 '26 23:01

Michael Krelin - hacker