Home > other >  What is happening in this pointer to string compare function?
What is happening in this pointer to string compare function?

Time:06-08

int compare(const void *a, const void *b)
{
    const char **str_a = (const char **)a;
    const char **str_b = (const char **)b;
    return strcmp(*str_a, *str_b);
}

I know that this function is comparing the contents of an array of pointers to string. But I am not getting what is going on inside it - I am confused about the **, why it is used?

CodePudding user response:

This is the typical callback function required by bsearch/qsort, which passes along two pointers to array items, to be compared by this function. It returns less than zero, zero or greater than zero if the first item is considered lesser, equal or greater than the second.

Now lets your array that needs searching/sorting is an array of pointers, such as a typical array of strings: char* arr[] = { "hello", "world" };

Then each item in this array is a char*. Meaning bsearch/qsort will pass a pointer to a character pointer, const char**, to the callback function.

Since void* specifically is a generic pointer, this is fine. We are allowed to convert from const char** to const void* and back. But we can't anything meaningful with a const void* so it needs to be cast to the expected type, then de-referenced so that strcmp gets two const char* parameters like it expects.

CodePudding user response:

The function expects arguments to be pointers to pointers. Example use:

const char *a = "string";
const char *b = "string";
int result = compare(&a, &b);

Another example:

int main(int argc, char *argv[]) {
    assert(argc >= 3);
    return compare(&(argv[1]), &(argv[2]));
}
  • Related