Path: ...!Xl.tags.giganews.com!local-1.nntp.ord.giganews.com!nntp.brightview.co.uk!news.brightview.co.uk.POSTED!not-for-mail NNTP-Posting-Date: Thu, 15 Aug 2024 16:43:16 +0000 From: Mark Summerfield Subject: Re: why does bsearch segfault on custom strcmp when qsort works fine? Newsgroups: comp.lang.c References: MIME-Version: 1.0 User-Agent: Pan/0.149 (Bellevue; 4c157ba) Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Message-ID: Date: Thu, 15 Aug 2024 16:43:16 +0000 Lines: 36 X-Usenet-Provider: http://www.giganews.com X-Trace: sv3-ilYoLwgGWaFSHXEa/SiQpJzoA7OfKondn+wjoBRGfwZESfyepUCMbxP24TQGavLEiMhTR3W9aPw3JM8!y/A5IYYA3cRH3zQAB5j+9wjP9M77D1VAXtECNZriI2mIA07OSyoWLKrjvu/si83mBylppxPB799k!mazcu6MKEqDKs7hwb4D1BaUkPQ== X-Abuse-and-DMCA-Info: Please be sure to forward a copy of ALL headers X-Abuse-and-DMCA-Info: Otherwise we will be unable to process your complaint properly X-Postfilter: 1.3.40 Bytes: 2243 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; }