Re: why does bsearch segfault on custom strcmp when qsort works fine?

Liste des GroupesRevenir à l c 
Sujet : Re: why does bsearch segfault on custom strcmp when qsort works fine?
De : mark (at) *nospam* qtrac.eu (Mark Summerfield)
Groupes : comp.lang.c
Date : 15. Aug 2024, 18:43:16
Autres entêtes
Message-ID : <Ut2dnVXgm4G5rSP7nZ2dnZfqn_WdnZ2d@brightview.co.uk>
References : 1 2
User-Agent : Pan/0.149 (Bellevue; 4c157ba)
On Thu, 15 Aug 2024 08:55:45 -0000 (UTC), Ike Naar wrote:

[snip]
The elements of the words array have type pointer-to-char.
So the first argument to bsearch should be the address of such an
element, that is,
a pointer-to-pointer-to-char and it should contain the adress of a
pointer to the first character of the oscar string.
Also, the value returned from bsearch should be interpreted as a
pointer-to-pointer-to-char.
 
    char * key = "oscar";
    char * * p = bsearch(&key, words, size, sizeof(char*), mystrcmp);
 
    index = p - words[0];
    found = p != NULL:
 
Two problems here: first, if bsearch returns NULL, the subtraction is
ill-defined.
Second, if bsearch returns non-null the index will be p - words, not p -
words[0];
 
    found = p != NULL:
    if (found) index = p - words;

Thank you! That solved the problem and clarified my mistakes.
By changing the code along the suggested lines it works great:

    char* s = "oscar";
    char** p = bsearch(&s, words, size, sizeof(char*), mystrcmp);
    if (p) {
        index = p - words;
        found = true;
    }



Date Sujet#  Auteur
15 Aug 24 * why does bsearch segfault on custom strcmp when qsort works fine?5Mark Summerfield
15 Aug 24 +* Re: why does bsearch segfault on custom strcmp when qsort works fine?2Ike Naar
15 Aug 24 i`- Re: why does bsearch segfault on custom strcmp when qsort works fine?1Mark Summerfield
15 Aug 24 `* Re: why does bsearch segfault on custom strcmp when qsort works fine?2Richard Harnden
15 Aug 24  `- Re: why does bsearch segfault on custom strcmp when qsort works fine?1Michael S

Haut de la page

Les messages affichés proviennent d'usenet.

NewsPortal