[英]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. 我试图通过char对结构运行数组进行排序,但是当我打印数组时,没有任何内容被排序。 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 上面的输出只是按照最初放置的顺序列出的名称
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. 这并不能让你在数组上使用
sizeof
,因为数组会被衰减为指针。
This 这个
run *run1 = *(run **)a;
also looks weird, shouldn't it be 也看起来很奇怪,不应该
run *run1 = (run*)a;
? ?
One problem is in name_compare
. 一个问题是在
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);
}
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. 正如@michel所提到的,sizeof(array)提供了指针的大小,而不是数组本身的大小,因为在传递数组时它被视为指针。 Hence either send the number of elements to the function count_number_of_different_persons or define a MACRO of number of elements.
因此,要么将元素数发送到函数count_number_of_different_persons,要么定义元素数量的MACRO。 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));
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.