Is there anyway to do something like this?
int key=50;
int loop=5;
int array[10]={...};
int* Ptr=NULL;
qsort(array, 10, sizeof(int), compareints);
while(loop>0){
Ptr=(int*)bsearch(&key,array,10,sizeof(int),compareints);
if(Ptr!=NULL){
printf("found %d", *Ptr);
}else{
printf("did not find %d", *Ptr);
}
key++;
loop--;
}
Problem is key gets incremented, but bsearch
still searches for the number 50. I'm guessing because the key argument in bsearch
is a constant pointer
.
I know it works if all the keys are stored in an array prior to searching. However, this doesn't suit my application. Any help would be appreciated.
Transcribing comment — and adding demonstration code.
You should be able to search for any key on any given iteration of your loop, so you need to show why you think it is still searching for 50...maybe you need to show what's in your array's initializer? Could it be that your
compareints()
function is misbehaving? Maybe you should show that, too? Your 'did not find' print should be printingkey
not*Ptr
. Bothprintf()
format strings should end with\n
for sanity's sake.This code works — and doesn't significantly change the logic shown in your question:
Sample output: