Sujet : Re: why does bsearch segfault on custom strcmp when qsort works fine?
De : mark (at) *nospam* qtrac.eu (Mark Summerfield)
Groupes : comp.lang.cDate : 15. Aug 2024, 17: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;
}