Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.c > #387587
| From | Mark Summerfield <mark@qtrac.eu> |
|---|---|
| Subject | Re: why does bsearch segfault on custom strcmp when qsort works fine? |
| Newsgroups | comp.lang.c |
| References | <UQWdnfwQxtYABSD7nZ2dnZfqnPadnZ2d@brightview.co.uk> <slrnvbrgkg.qdu.ike@iceland.freeshell.org> |
| Message-ID | <Ut2dnVXgm4G5rSP7nZ2dnZfqn_WdnZ2d@brightview.co.uk> (permalink) |
| Date | 2024-08-15 16:43 +0000 |
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;
}
Back to comp.lang.c | Previous | Next — Previous in thread | Next in thread | Find similar
why does bsearch segfault on custom strcmp when qsort works fine? Mark Summerfield <mark@qtrac.eu> - 2024-08-15 05:56 +0000
Re: why does bsearch segfault on custom strcmp when qsort works fine? Ike Naar <ike@sdf.org> - 2024-08-15 08:55 +0000
Re: why does bsearch segfault on custom strcmp when qsort works fine? Mark Summerfield <mark@qtrac.eu> - 2024-08-15 16:43 +0000
Re: why does bsearch segfault on custom strcmp when qsort works fine? Richard Harnden <richard.nospam@gmail.invalid> - 2024-08-15 10:06 +0100
Re: why does bsearch segfault on custom strcmp when qsort works fine? Michael S <already5chosen@yahoo.com> - 2024-08-15 15:10 +0300
csiph-web