gpt4 book ai didi

C bsearch 总是返回 pointer=NULL

转载 作者:太空宇宙 更新时间:2023-11-04 03:21:57 25 4
gpt4 key购买 nike

有人能告诉我为什么在这个程序中 bsearch 函数总是返回 pointer=NULL 吗??

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

struct data
{
char name[10];
int age;
char eye[15];
};



int komparator (const void* a, const void *b)
{
struct data *aa = (struct data *)a;
struct data *bb = (struct data *)b;
return (aa->age-bb->age);
}

int main ()
{
char *NAME[10]={"Ola","Tola","Jola","Zosia","Jan","Adam","Ala","Basia","Tom","Jacek"};
char *COLOR[10]={"zielone", "brazowe", "niebieskie", "niebieskie", "zielone", "brazowe", "brazowe", "niebieskie", "czarne", "niebieskie"};

struct data (*pointer)[5];
struct data people[2][5];
pointer=people;

int i;
for(i=0;i<2*5;i++)
{
strcpy((*pointer)[i].name,NAME[i]);
strcpy((*pointer)[i].eye,COLOR[i]);
(*pointer)[i].age=rand()%(40-18)+18;
}

qsort(people,2*5,sizeof(struct data),komparator);

// here is the problem:
int wanted = 18;
struct data *found=(struct data*) bsearch(&wanted,people,2*5,sizeof(struct data),komparator);

if(found!=NULL)
{
printf("Found name is: %s, eye's: %s, age: %d\n",found->name,found->eye,found->age);
}
else
{
printf("Didnt find \n");
}
return 0;
}

请专注于 bsearch 部分,因为其他方面工作正常。

我将不胜感激:)

最佳答案

这个问题的解决方法是komparator需要type(struct data *),所以

int wanted=18;

是错误的,改成

struct data wanted = {"", 18, ""};

一切正常:)

@BLUEPIXY 帮助了 :)

关于C bsearch 总是返回 pointer=NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44834031/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com