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

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

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

Disclosure: My content contains affiliate links.

43,700 questions

57,013 answers

573 users

How to use the bsearch function to search an array for an element of an unspecified type in C

1 Answer

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

// Example structure representing an arbitrary/unspecified data type
typedef struct {
    int id;
    char name[32];
} Item;

/**
 * Comparison function required by bsearch.
 * Compares two Item elements by their ID.
 * 
 * @return Negative if a < b, 0 if a == b, Positive if a > b.
 */
int compare_items(const void *a, const void *b) {
    const Item *item_a = (const Item *)a;
    const Item *item_b = (const Item *)b;
    
    return (item_a->id - item_b->id);
}

/**
 * Generic wrapper function for bsearch to find an element in a sorted array.
 * 
 * @param key Pointer to the target element being searched for.
 * @param base Pointer to the first element of the array.
 * @param nitems Number of elements in the array.
 * @param size Size of each individual element in bytes.
 * @return Pointer to the matched element, or NULL if not found.
 */
void* find_element(const void *key, const void *base, size_t nitems, size_t size, 
                   int (*compar)(const void *, const void *)) {
    // bsearch performs a binary search on the sorted array
    return bsearch(key, base, nitems, size, compar);
}

int main(void) {
    // The array MUST be sorted prior to calling bsearch
    Item inventory[] = {
        {101, "Laptop"},
        {205, "Mouse"},
        {310, "Keyboard"},
        {420, "Monitor"}
    };
    size_t num_items = sizeof(inventory) / sizeof(inventory[0]);

    // Define the key we are looking for
    Item search_key = {310, ""};

    // Call our search wrapper function
    Item *result = (Item *)find_element(&search_key, inventory, num_items, sizeof(Item), compare_items);

    if (result != NULL) {
        printf("Found item: ID = %d, Name = %s\n", result->id, result->name);
    } else {
        printf("Item not found.\n");
    }

    return 0;
}


/*
run:

Found item: ID = 310, Name = Keyboard

*/

 



answered 2 days ago by avibootz

Related questions

1 answer 325 views
1 answer 224 views
2 answers 193 views
193 views asked Mar 3, 2024 by avibootz
1 answer 176 views
1 answer 176 views
...