1

第一次使用 bsearch() 我想知道有没有办法找到元素的位置或返回元素?

我有 bsearch() 工作,它返回一个指针,但我不能用它来打印元素。

void choose_food_item(){
char food[20];
int qty;
int size = sizeof (food_stuff_choices) / sizeof (*fs);
char * ptr_item;
do{
printf("\nPlease Choose Your Food Items!!! When finished enter display to view plan\n");
fflush(stdout);
gets(food); // searchkey

/* sort the elements of the array */
qsort(food_stuff_choices,size,sizeof(*fs),(int(*)(const void*,const void*)) strcmp);

/* search for the searchkey */
ptr_item = (char*)
bsearch (food,food_stuff_choices,size,sizeof(*fs),(int(*)(const void*,const void*)) strcmp);

if (ptr_item!=NULL){
    //printf("%d\n",(int)*ptr_item);
    printf("Please Enter Quantity\n");
    fflush(stdout);
    scanf("%d",&qty);
    food_plan_item item = {food_stuff_choices[0], qty};
    add_food_plan_item(item);
}
else
    printf ("%s not found in the array.\n",food);

}while(strcmp("display",food) != 0);
}
4

2 回答 2

2

bsearch返回一个指向找到的元素的指针。

从第零个元素的地址中减去该地址。

然后除以元素的长度。

这为您提供了元素的下标。

于 2013-12-13T16:21:13.927 回答
0

您可以使用

pos=((int)ptr_item-(int)food_stuff_choices)/sizeof(char);

说明: 这将获取bsearch()返回的元素的地址并将其转换为整数,然后获取数组的第一个元素位置的地址并将其转换为整数。然后取两者的差异并除以列表数据类型的大小,即 char

此代码将为您提供pos,它是数组中元素的位置

如果您只想打印值(不需要位置),那么下面的代码对您有好处:

printf("%s",*food_stuff_choices);
于 2017-04-26T06:55:23.993 回答