carraysstructbsearch

How to search an array within a structure using bsearch in c


Please help I don't understand why I can't search an element in an array within a structure to another array within another structure. Thank you for your help guys would really appreciate it.

#include<stdio.h>
#include<stdlib.h>
#define MAX 10

typedef struct{
    int elements[MAX];
    int count;
}SET;

int cmpfunc(const void * a, const void * b) {
   return (*(int*)a > *(int*)b) - (*(int*)a < *(int*)b);
}

void print(SET *s1, SET *s2){
    int *p;
    p = bsearch(&s2->elements[1],&s1->elements,s1->count,sizeof(s1->elements),cmpfunc);
    printf("%p",p);

    return;
}

int main () {
    SET s1 = {{5,20,29,32,63},5};
    SET s2 = {{1,29,3,5},4};

    print(&s1,&s2);

   return(0);
}

Solution

  • You need to use

    sizeof(*s1->elements)
    

    that is the same as

    sizeof( int )
    

    instead of

    sizeof(s1->elements)
    

    in the call of bsearch.

    Also instead of

    &s1->elements
    

    use

    s1->elements
    

    The call will look like

    bsearch( &s2->elements[1], s1->elements, s1->count, sizeof(*s1->elements), cmpfunc );
    

    Pay attention to that the conversion specifier %x may not be used with pointers. Use either %p or dereference the found pointer and use %x provided that the target value is found.