Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is happening in this pointer to string compare function?

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?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading