Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

40,026 questions

51,982 answers

573 users

How to use bsearch() to find an element in struct array in C

1 Answer

0 votes
#include <stdlib.h>
#include <stdio.h>

// void* bsearch(const void *key, const void *ptr, size_t count, size_t size,
//               int (*comp)(const void*, const void*));

/*
key - pointer to the struct to search for
ptr - pointer to the array of structs
count - number of element in the array
size - size of each element in the array in bytes
comp - comparison function
*/
 
struct data 
{
    int n;
    char const *lang;
} dat[] = { {1, "C"}, {2, "C++"}, {3, "C#"}, {4, "Java"}, {5, "PHP"} };
 
int data_cmp(void const *f_data, void const *s_data) 
{
    struct data const *const first = f_data;
    struct data const *const second = s_data;
 
    if (first->n < second->n) return -1;
    else if (first->n > second->n) return 1;
    else return 0;
}
 
int main(void) 
{
    struct data p_lang = { .n = 3 };
    struct data const *p = bsearch(&p_lang, dat, sizeof dat / sizeof dat[0], 
                                   sizeof dat[0], data_cmp);
    
    if (p) {
        printf("Number %d is: %s\n", p->n, p->lang);
    } else {
        printf("Number %d not found\n", p_lang.n);
    }
    
    return 0;
}
  
/*
run:
 
Number 3 is: C#

*/

 



answered Aug 26, 2016 by avibootz

Related questions

2 answers 88 views
88 views asked Mar 3, 2024 by avibootz
1 answer 95 views
1 answer 170 views
2 answers 157 views
1 answer 172 views
172 views asked May 6, 2019 by avibootz
1 answer 165 views
...