Thread: bsearch( ) and qsort( ) not agreeing

  1. #1
    Registered User
    Join Date
    Sep 2004
    Posts
    20

    bsearch( ) and qsort( ) not agreeing

    I'm making a program that's supposed to have a binary search of an array that has already been sorted by qsort( ). The qsort( ) function worked perfectly and outputted the correct sorted array, but the bsearch( ) using the same "compare" function does not seem to work correctly. I've been reading that these two functions use the same compare function together when dealing with the same types of elements. Can anyone tell me what I'm doing wrong with my bsearch function?
    Code:
    struct ot_entry {
         char  ot_mnemonic[OP_LENGTH + 1];
         int   ot_format; 
    };
    struct  ot_entry  *optbl[OT_SIZE]; 
    
    int compare_elements(const void **ptr1, const void **ptr2){
        return strcmp((*(struct ot_entry**)ptr1)->ot_mnemonic, (*(struct ot_entry**)ptr2)->ot_mnemonic);
    }  
    
    // sort elements by the ot_mnemonic string in ot_entry
    void sortOpTbl(){    
        qsort(optbl, ot_count, sizeof(optbl[0]), compare_elements);
        
    }
    
    // find element by the ot_mnemonic string in ot_entry
    void find_operation (const char *name)
    {
      struct ot_entry target, *result;
      strcpy(target->ot_mnemonic, name);
      result = bsearch (&target, optbl, ot_count, sizeof (struct ot_entry), compare_elements);
      
      if (result){
        printf("Operation %s was found", name);
      }    
      else{      
        printf ("Couldn't find %s.\n", name);
      }    
    }
    
    
    int main( ){
       ...
        
       char oper[OP_LENGTH + 1];
    
       find_operation(oper);
       
       ...
       return 0;
    }

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Well for starters, your compare takes the wrong arguments for both qsort and bsearch.
    Code:
    void *bsearch(const void *key, const void *base, size_t nmemb,
                  size_t size, int (*compar)(const void *, const void *));
    
    void qsort(void *base, size_t nmemb, size_t size,
                  int (*compar)(const void *, const void *))
    And this is what you're trying to use:
    Code:
    int compare_elements(const void **ptr1, const void **ptr2)
    Don't you listen to your compiler ever? It should be having a fit.

    Quzah.
    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem Using bsearch
    By Zildjian in forum C Programming
    Replies: 4
    Last Post: 11-13-2003, 08:14 PM
  2. Replies: 7
    Last Post: 04-13-2003, 10:53 PM