Question

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.

Was it helpful?

Solution

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 printing key not *Ptr. Both printf() format strings should end with \n for sanity's sake.

This code works — and doesn't significantly change the logic shown in your question:

#include <stdlib.h>
#include <stdio.h>

static
int compareints(const void *v1, const void *v2)
{
    int i1 = *(int *)v1;
    int i2 = *(int *)v2;
    if (i1 < i2)
        return -1;
    else if (i1 > i2)
        return +1;
    else
        return 0;
}

int main(void)
{
    int key = 50;
    int loop = 5;
    int array[10] = { 57, 49, 50, 51, 53, 27, 60, 51, 19, 99 };
    int *ptr = NULL;

    for (int i = 0; i < 10; i++)
        printf("%3d", array[i]);
    putchar('\n');
    qsort(array, 10, sizeof(int), compareints);
    for (int i = 0; i < 10; i++)
        printf("%3d", array[i]);
    putchar('\n');

    while (loop > 0)
    {
        printf("seeking key %d: ", key);
        ptr = (int *)bsearch(&key, array, 10, sizeof(int), compareints);

        if (ptr != NULL)
            printf("found %d\n", *ptr);
        else
            printf("did not find %d\n", key);
        key++;
        loop--;
    }
    return 0;
}

Sample output:

 57 49 50 51 53 27 60 51 19 99
 19 27 49 50 51 51 53 57 60 99
seeking key 50: found 50
seeking key 51: found 51
seeking key 52: did not find 52
seeking key 53: found 53
seeking key 54: did not find 54
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top