cbsearch

Is there a way of finding position of element when searching a char array with bsearch()


First time using bsearch() and i was wondering is there a way of finding the position of the element or return the element??

I have bsearch() working and it returns a pointer but from this i am not able to use it to print the element.

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);
}

Solution

  • bsearch returns a pointer to the found element.

    Subtract that address from the address of the zeroth element.

    Then divided by the length of the element.

    That gives you the subscript to the element.