Mail Archives: djgpp/1997/02/04/02:24:21
I wanted to use 'bsearch' on an ordered set of structures. using a
member of the structure as a key. I tried:
typedef struct {
long lElement;
....
}ANYSTRUCT;
ANYSTRUCT anyStruct, *pArray, *anyElem;
int main()
{
pArray = malloc( size * sizeof(ANYSTRUCT) );
....
anyElem =
bsearch( (void *)anySTruct->lElement, pArray, size, sizeof(ANYSTRUCT),
bSearchFunc);
It did not work. The pointer to the key value that bSearchFunc received
was some rubbish. Then I tried
bsearch( &(anySTruct->lElement), pArray, size, sizeof(ANYSTRUCT),
bSearchFunc_1);
which also did not work correctly (bSearchFunc_1 differs from
bSearchFunc, because it receives a pointer and not a value casted to a
pointer). The working solution was:
l = anySTruct->lElement;
bsearch( (void *)l, pArray, size, sizeof(ANYSTRUCT),
bSearchFunc);
Is this a correct behaviour of bsearch? Or is this a compiler bug? I
compiled without optimization with -Wall and -g. Gdb has shown that the
argument of bsearch was incorrect in the first two cases.
Andras
- Raw text -