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

StackOverflow https://stackoverflow.com/questions/20571043

  •  01-09-2022
  •  | 
  •  

سؤال

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);
}
هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

you can use

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

Explanation: this will take address of your element returned by bsearch() and typecast it in integer then it take the address of first element position your array and convert it in integer. then take difference of both and divide by the size of your list datatype i.e, char

this code will give you pos which is the position of element in array

if you only want to print the value (no need of position) then the below code will be good for you:

printf("%s",*food_stuff_choices);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top