How would you use bsearch() function to search a name stored in array of pointers to string?



How would you use bsearch() function to search a name stored in array of pointers to string?..

Answer / Rajendra Kumar Nishad

To use the bsearch() function, you need to provide a comparison function similar to qsort(). Here's an example:

```cn
#include <stdio.h>n
#include <stdlib.h>n
n
typedef struct {n char *name;n } Person;n
n
int compareNames(const void *a, const void *b, const void *c)n{n return strcmp(((Person *) a)->name,n ((Person *) b)->name) - (*(const char **) c);n}n
n
int main() {n Person people[] = {"Alice", "Bob", "Charlie", "Dave"};n const Person *person = bsearch(&"Eve", people, sizeof(people) / sizeof(people[0]), sizeof(Person), compareNames);n if (person != NULL) {n printf("%s found.
", person->name);n } else {n printf("Not found.
");n }n}n ```

Is This Answer Correct ?    0 Yes 0 No

Post New Answer

More Data Structures Interview Questions

What is stack push?

1 Answers  


Which is better hashset or treeset?

1 Answers  


Why do we use linked lists?

1 Answers  


What do you mean by linear probing?

1 Answers  


What is a node in it?

1 Answers  


Define depth and height of a node?

1 Answers  


What do you mean by tree edge?

1 Answers  


Which is better merge or quick sort?

1 Answers  


Write is a binary search tree? Write an algorithm and tell complexity?

1 Answers   ITC Indian Tobacco Company,


What are the advantages of array?

1 Answers  


Differentiate between set and map.

1 Answers  


State the different types of linked lists?

1 Answers  


Categories