qsort of struct array not working

2019-07-20 14:24发布

问题:

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

回答1:

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;

?



回答2:

One problem is in name_compare. Try this instead:

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


回答3:

Check the following code:

As @michel mentioned, sizeof(array) provides size of the pointer, not the size of the array itself, as while passing array it is treated as a pointer. Hence either send the number of elements to the function count_number_of_different_persons or define a MACRO of number of elements. Hope this helps. :).

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define NOE 3

struct run
{
    char name[20];
};

typedef struct run run;

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

int count_number_of_different_persons(run results[], int noOfElements)
{
    int i=0;
    qsort(results, noOfElements, sizeof (run), name_compare);
    for (i=0; i<noOfElements; i++)
        printf ("%s\n",results[i].name);
}

int main ( int argc, char * argv[])
{
    run a, b, c;
    run  arg[NOE];

    strcpy (a.name, "love");
    strcpy (b.name, "you");
    strcpy (c.name, "i");
    arg[0] = a;
    arg[1] = b;
    arg[2] = c;

    count_number_of_different_persons(arg, sizeof(arg)/sizeof(run));
};