Course contentsShow
← C
Lesson 881 of 1,21912. The Standard LibraryFree lesson

Handling the `void*` return of `bsearch`

Handling the void* return of bsearch

What you'll learn: How to safely capture and convert the generic pointer returned by the binary search function into a usable data type.

The Mystery Box

When you use bsearch() to find an item in an array, the function doesn't know what kind of data you are searching through. It treats everything as raw memory. Because of this, it returns a void* (a "generic pointer").

Think of a void* like a wrapped gift box. You know there is something inside, but you can’t use it until you unwrap it and tell the compiler what it is. If the search finds a match, it returns the memory address of that element; if it finds nothing, it returns NULL.

Step 1: The Null Check

Before you try to use the result, you must check if it is NULL. If you try to access the memory of a NULL pointer, your program will crash. Always treat the return value as "potentially empty" first.

Step 2: Casting and Dereferencing

Once you know you have a valid pointer, you need to tell C what type of data is living at that address. You do this by creating a pointer of your specific type and setting it equal to the search result. C allows void* to be converted to other pointer types automatically, but you still need to perform this step to access the actual values.

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

int main() {
    int numbers[] = {10, 20, 30, 40, 50};
    int key = 30;

    // bsearch returns a void*
    void *result = bsearch(&key, numbers, 5, sizeof(int), compare_ints);

    if (result != NULL) {
        // Convert void* to int* so we can actually use the number
        int *found_ptr = (int *)result;
        printf("Found value: %d\n", *found_ptr);
    } else {
        printf("Value not found.\n");
    }

    return 0;
}

Bridging the Gap

The reason we perform this "cast" (converting void* to int*) is that a void* has no size. If you try to do *result, the compiler will complain because it doesn't know how many bytes to read. By assigning the result to an int*, you are telling the compiler, "Hey, this address points to a 4-byte integer."

Key takeaway

Always check if bsearch returned NULL before assigning its result to a typed pointer to access your data.