stdlib.h中的qsort()未对包含邮政编码和相应城市的特殊结构进行排序

问题描述 投票:0回答:2

我正在用全球危机来学习我的学习书之外的C语言,并且我正在学习一本德语书籍(Rheinwerk Computing:C von A bis Z,ANSI-C99),并最终达到了搜索功能。作为一种实践,我想实现一种排序功能以提供binaray搜索的功能。

我的问题是,每当我添加新的zip结构时,它们都不会被分类。我已经在这里浏览了不同的问题,并发现了如何为结构构建比较函数以及如何使用qsort处理结构。但似乎答案无济于事,否则我很可能会放弃查看它。

技术环境:我在Windows的32位Debian子系统上使用vim和gcc(标志:-Wpedantic -Wstrict-aliasing -Wshadow -Wcast-align -Wextra -Wfloat-equal)。由于gcc在编译代码时没有抱怨任何东西,所以我想知道我做错了什么。

我的代码:

struct zipc
{
   char place[255];
   unsigned int zip;
};

struct zipc zipcodes[100];

static int N; //Counting how many adresses are already typed in

// create new zip with city, init function creates one with N=0 and dummy values

void insertbs(unsigned int p, char *o) 
{
    zipcodes[++N].zip = p;
    strcpy(zipcodes[N].place, o);
}

int cmp_uinteger(const void *value1, const void *value2)
{
   const struct zipc *p1 = value1;
   const struct zipc *p2 = value2;

   if(p1->zip > p2->zip) 
        return 1;
   if(p2->zip > p1->zip)
        return (-1);
   else 
        return 0;
}

//usage of qsort later in main

qsort(zipcodes, N-1, sizeof(unsigned int), cmp_uinteger);

cmp_uinteger函数受到此处另一个问题的启发,看起来很不错,但排序始终会失败,但不会导致程序失败。该程序正在运行,但如果以任意顺序插入邮政编码,二进制搜索将失败,这就是为什么我认为它与qsort()有关,但我虽然可以在其他地方。我认为我不太了解比较功能,也许有人也可以解释。

在这里发布我的第一个问题感到很奇怪,因为在C教程中,堆栈溢出成为我的第二故乡:D

最好的问候,恶意软件

c qsort
2个回答
0
投票
qsort(zipcodes, N-1, sizeof(unsigned int), cmp_uinteger);

qsort()的第三个参数“数组中每个元素的大小(以字节为单位)”

在您的情况下,应为sizeof(struct zipc)而不是sizeof(unsigned int)


0
投票

使用zipcodes[0]处的虚拟值,从zipcodes + 1进行排序,并使用数组元素的大小。

// qsort(zipcodes, N-1, sizeof(unsigned int), cmp_uinteger);
qsort(zipcodes + 1, N-1, sizeof zipcodes[0], cmp_uinteger);
© www.soinside.com 2019 - 2024. All rights reserved.