a small bsearch example

  • Thread starter Ramprasad A Padmanabhan
  • Start date
R

Ramprasad A Padmanabhan

I have written a simple script to search a word in an array But bsearch
does not seem to work here.

I know I am missing out something very simple , But I am not able to
find out what

Thanks
Ram


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

int cmp1(const void *p1, const void *p2)
{
char *s = p1;
char *target = p2;
printf("Comparing %s ==> %s \n",s,target);
return(strcmp(s,target));
}

int main(int argc,char* argv[]){
int i=0;
char* find[] = {"a.c","b.c","c.c","END"};
char* words[] ={"a.c","b.c","c.c","zzz"};

while(strcmp(find,"END") != 0){
char *tmp;
tmp = bsearch(find, words, 4,4, cmp1);
printf("Finding word %s\t==>\t Got %s\n",find,tmp);
i++;
}
return(0);
}

My output looks like this
Finding word a.c ==> Got (null)
Finding word b.c ==> Got (null)
Finding word c.c ==> Got (null)
 
M

Mark Gordon

I have written a simple script to search a word in an array But
bsearch does not seem to work here.

I know I am missing out something very simple , But I am not able to
find out what

Thanks
Ram


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

You don't need all of these headers, although including a standard
header you don't need is not going to break any otherwise well written
code.
int cmp1(const void *p1, const void *p2)
{
char *s = p1;
char *target = p2;

char *target = *(char**)p2;

Each of your elements in words is a pointer to a char* and bsearch
passes you a pointer to the element, so you are getting a pointer to a
pointer to char which you want to dereference.
printf("Comparing %s ==> %s \n",s,target);
return(strcmp(s,target));
}

int main(int argc,char* argv[]){
int i=0;
char* find[] = {"a.c","b.c","c.c","END"};
char* words[] ={"a.c","b.c","c.c","zzz"};

while(strcmp(find,"END") != 0){
char *tmp;


char **tmp;

Again, bsearch returns a pointer to the found element.
tmp = bsearch(find, words, 4,4, cmp1);
printf("Finding word %s\t==>\t Got %s\n",find,tmp);


if (tmp)
printf("Finding word %s\t==>\t Got %s\n",find,*tmp);
else
printf("Finding word %s\t==>\t Failed\n",find);

Otherwise if the find fails any you get back a null pointer you are
invoking undefined behaviour and anything could happen. You are just
lucky that your implementation decided to print (null) rather than
causing a small thermonuclear explosion.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top