SDL_bsearch(3)

✨ NAME ✨

SDL_bsearch β€” bestie, this is the glow-up version of a binary search: you hand it an array you already sorted, and it finds your element in it. πŸ’–

This one lives in the SDL3 FUNCTIONS family, so you already know it's giving main character energy.


🌸 SYNOPSIS 🌸

#include <SDL3/SDL_stdinc.h>

void * SDL_bsearch(const void *key, const void *base, size_t nmemb, size_t size, SDL_CompareCallback compare);

πŸŽ€ DESCRIPTION πŸŽ€

okay so the vibe here is: binary search, but make it SDL. You give it a key, an array that has already been sorted, and a compare callback, and it goes hunting. πŸ’…

For example:

typedef struct {
    int key;
    const char *string;
} data;

int SDLCALL compare(const void *a, const void *b)
{
    const data *A = (const data *)a;
    const data *B = (const data *)b;

    if (A->n < B->n) {
        return -1;
    } else if (B->n < A->n) {
        return 1;
    } else {
        return 0;
    }
}

data values[] = {
    { 1, "first" }, { 2, "second" }, { 3, "third" }
};
data key = { 2, NULL };

data *result = SDL_bsearch(&key, values, SDL_arraysize(values), sizeof(values[0]), compare);

literally just: key in, sorted array in, compare function in, result out. periodt. ✨


πŸ¦‹ FUNCTION PARAMETERS πŸ¦‹

  • key β€” a pointer to a key that's equal to the element you're searching for. like, this is the thing you want a twin of. 🫢
  • base β€” a pointer to the start of the array. the beginning, the origin story, the front row. 🌈
  • nmemb β€” the number of elements in the array. how many besties are even in the room. πŸ’œ
  • size β€” the size of the elements in the array. (per element, not the whole thing β€” iykyk.) ⭐
  • compare β€” a function used to compare elements in the array. you write it, SDL calls it, they gossip about ordering. 😭

πŸ’€ RETURN VALUE πŸ’€

Returns a pointer to the matching element in the array, or NULL if not found.

so like… pointer = found, NULL = it's not here bestie, go home. πŸ™ˆ


🧚 THREAD SAFETY 🧚

It is safe to call this function from any thread. no cap. every thread can have a turn, no drama, no fighting. πŸ’–


πŸ‘‘ AVAILABILITY πŸ‘‘

This function is available since SDL 3.2.0. so if you're on something older than that… it's giving vintage, but not in the cute way. πŸ’€


πŸ“ SEE ALSO πŸ“


lowkey reminder bestie: it's a binary search, so the array has to be sorted first. SDL_qsort is right there in SEE ALSO for a reason. sort then search, in that order. πŸ’…

and that's the whole page, mwah πŸ’‹

Brought to you by the fine folks at Simple Directmedia Layer β€” this is from SDL 3.4.18, and the page itself is SDL_bsearch(3). go sort something and then find it, you icon. πŸŽ€βœ¨πŸ¦‹

πŸ“¦ where this page comes from