SDL_qsort_r(3)

πŸ’… SDL_qsort_r(3) β€” SDL3 FUNCTIONS ✨

okay bestie, sit down, hydrate, because we're sorting arrays and we're doing it with style. this is a page from the SDL3 FUNCTIONS collection, and today's main character is SDL_qsort_r β€” the sort that lets you slide a lil userdata pointer into your compare function like a note passed in class. 🫢


✨ NAME ✨

SDL_qsort_r β€” Sort an array, passing a userdata pointer to the compare function.

like, you sort stuff. but your compare function also gets a userdata pointer. that's the whole vibe. no cap. πŸ’–


πŸŽ€ SYNOPSIS πŸŽ€

#include <SDL3/SDL_stdinc.h>

void SDL_qsort_r(void *base, size_t nmemb, size_t size, SDL_CompareCallback_r compare, void *userdata);

πŸ¦‹ DESCRIPTION πŸ¦‹

okay so here's a whole example, and honestly? it eats. πŸ“

       typedef enum {
           sort_increasing,
           sort_decreasing,
       } sort_method;

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

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

           if (A->key < B->key) {
               return (method == sort_increasing) ? -1 : 1;
           } else if (B->key < A->key) {
               return (method == sort_increasing) ? 1 : -1;
           } else {
               return 0;
           }
       }

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

       SDL_qsort_r(values, SDL_arraysize(values), sizeof(values[0]), compare, (const void *)(uintptr_t)sort_increasing);

see how the userdata gets smuggled into compare and turned back into a sort_method? that's the entire point, bestie. you want increasing? decreasing? your compare function decides, and userdata tells it which way to go. iconic behavior, honestly. 🌈


πŸ’– FUNCTION PARAMETERS πŸ’–

  • base β€” a pointer to the start of the array. the beginning. the origin story. ✨
  • nmemb β€” the number of elements in the array. how many little guys we're sorting. πŸ”’
  • size β€” the size of the elements in the array. each one's lil footprint. πŸ‘Ÿ
  • compare β€” a function used to compare elements in the array. it does the judging (lovingly). πŸ’…
  • userdata β€” a pointer to pass to the compare function. your secret lil message. 🀫

🌸 THREAD SAFETY 🌸

It is safe to call this function from any thread. 🧚

go off, thread queen. every thread can sort. no gatekeeping here. πŸ’š


⭐ AVAILABILITY ⭐

This function is available since SDL 3.2.0. so if you're on something older… bestie, it's giving ✨upgrade✨. 😭


πŸ‘‘ SEE ALSO πŸ‘‘

the whole friend group, fr fr. 🫢


and that's the page!! this manual page came to you courtesy of Simple Directmedia Layer, straight from SDL 3.4.18. go sort something beautiful, bestie. πŸŽ€πŸ’–βœ¨

πŸ“¦ where this page comes from