Using qsort() and bsearch() with strings - example program in C

By: Manoj Kumar Emailed: 1727 times Printed: 2328 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

This program makes use of an array of pointers to strings.You can "sort" the strings by sorting the array of pointers. However, this method requires a modification in the comparison function. This function is passed pointers to the two items in the array that are compared. However, you want the array of pointers sorted based not on the values of the pointers themselves but on the values of the strings they point to.

Because of this, you must use a comparison function that is passed pointers to pointers. Each argument to comp() is a pointer to an array element, and because each element is itself a pointer (to a string), the argument is therefore a pointer to a pointer. Within the function itself, you dereference the pointers so that the return value of comp() depends on the values of the strings pointed to.

The fact that the arguments passed to comp() are pointers to pointers creates another problem. You store the search key in buf[], and you also know that the name of an array (buf in this case) is a pointer to the array. However, you need to pass not buf itself, but a pointer to buf. The problem is that buf is a pointer constant, not a pointer variable. buf itself has no address in memory; it's a symbol that evaluates to the address of the array. Because of this, you can't create a pointer that points to buf by using the address-of operator in front of buf, as in &buf.

What to do? First, create a pointer variable and assign the value of buf to it. In the program, this pointer variable has the name key. Because key is a pointer variable, it has an address, and you can create a pointer that contains that address--in this case, key1. When you finally call bsearch(), the first argument is key1, a pointer to a pointer to the key string. The function bsearch() passes that argument on to comp(), and everything works properly.

1: /* Using qsort() and bsearch() with strings. */
3: #include <stdio.h>
4: #include <stdlib.h>
5: #include <string.h>
7: #define MAX 20
9: int comp(const void *s1, const void *s2);
11: main()
12: {
13:     char *data[MAX], buf[80], *ptr, *key, **key1;
14:     int count;
16:     /* Input a list of words. */
18:     printf("Enter %d words, pressing Enter after each.\n",MAX);
20:     for (count = 0; count < MAX; count++)
21:     {
22:         printf("Word %d: ", count+1);
23:         gets(buf);
24:         data[count] = malloc(strlen(buf)+1);
25:         strcpy(data[count], buf);
26:     }
28:     /* Sort the words (actually, sort the pointers). */
30:     qsort(data, MAX, sizeof(data[0]), comp);
32:     /* Display the sorted words. */
34:     for (count = 0; count < MAX; count++)
35:         printf("\n%d: %s", count+1, data[count]);
37:     /* Get a search key. */
39:     printf("\n\nEnter a search key: ");
40:     gets(buf);
42:     /* Perform the search. First, make key1 a pointer */
43:     /* to the pointer to the search key.*/
45:     key = buf;
46:     key1 = &key;
47:     ptr = bsearch(key1, data, MAX, sizeof(data[0]), comp);
49:     if (ptr != NULL)
50:         printf("%s found.\n", buf);
51:     else
52:         printf("%s not found.\n", buf);
53:     return(0);
54: }
56: int comp(const void *s1, const void *s2)
57: {
58:     return (strcmp(*(char **)s1, *(char **)s2));
59: }
Enter 20 words, pressing Enter after each.
Word 1: apple
Word 2: orange
Word 3: grapefruit
Word 4: peach
Word 5: plum
Word 6: pear
Word 7: cherries
Word 8: banana
Word 9: lime
Word 10: lemon
Word 11: tangerine
Word 12: star
Word 13: watermelon
Word 14: cantaloupe
Word 15: musk melon
Word 16: strawberry
Word 17: blackberry
Word 18: blueberry
Word 19: grape
Word 20: cranberry
1: apple
2: banana
3: blackberry
4: blueberry
5: cantaloupe
6: cherries
7: cranberry
8: grape
9: grapefruit
10: lemon
11: lime
12: musk melon
13: orange
14: peach
15: pear
16: plum
17: star
18: strawberry
19: tangerine
20: watermelon
Enter a search key: orange
orange found.

DON'T forget to put your search array into ascending order before using bsearch().

C Home | All C Tutorials | Latest C Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.

Bookmark and Share


1. View Comment

Hi, a have a problem using bsearch. i need return value like index of the element that was fount....something like "The number exists in the ARRAY, at idx 13".

How can i do this with func bsearch?

View Tutorial          By: Daniel at 2009-03-30 04:11:13
2. View Comment

Daniel, i think you need another func, also you can use '-' between arr address and the address of a element you need..

View Tutorial          By: רופא שיניים at 2009-08-15 16:48:07
3. View Comment

I agree with #2 u are missing that line

View Tutorial          By: ויזה לארה"ב at 2011-10-26 10:39:50

Your name (required):

Your email(required, will not be shown to the public):

Your sites URL (optional):

Your comments:

More Tutorials by Manoj Kumar
Importing Keystore example using keytool in Java
for loop example in Java
Result Sets, Cursors and Transactions in SQL
JSP Tags for SQL to connect to a database
Using the qsort() and bsearch() functions with values - example program in C
Using qsort() and bsearch() with strings - example program in C
scanf and sscanf sample program in C
Use of {0} is required and Accessing resource bundles programmatically in Struts
Character Arrays in C
Pointers to functions in C++
atoi(), itoa() in C++
Ticker sample program in J2ME
DateFormat sample program in Java
Random class sample program in Java - nextGaussian(), nextBoolean(), nextBytes(), nextInt(), nextLong(), nextFloat(), nextDouble()
What Is a Reference in C++?

More Tutorials in C
Sum of the elements of an array in C
Printing a simple histogram in C
Sorting an integer array in C
Find square and square root for a given number in C
Simple arithmetic calculations in C
Command-line arguments in C
Calculator in C
Passing double value to a function in C
Passing pointer to a function in C
Infix to Prefix And Postfix in C
while, do while and for loops in C
Unicode and UTF-8 in C
Formatting with printf in C
if, if...else and switch statements in C with samples
Statements in C

More Latest News
Most Viewed Articles (in C )
Using memset(), memcpy(), and memmove() in C
lseek() sample program in C
perror() Function - example program in C
UNIX read and write system calls sample program in C
assert() Function Example program in C
Find square and square root for a given number in C
Printing a simple histogram in C
Arrays of Structures example program in C
Listing Files and Directories sample program in C
scanf and sscanf sample program in C
Character Arrays in C
External Variables and Scope in C
goto and labels in C
Open, Creat, Close, Unlink system calls sample program in C
Using calloc() Function in C
Most Emailed Articles (in C)
scanf and sscanf sample program in C
Line Counting sample program in C
union example program in C
Variables and Arithmetic Expressions in C
Assignment Operators and Expressions in C
Command-line Arguments in C
Error Handling - Stderr and Exit - sample program in C
A Storage Allocator sample program in C
Using memset(), memcpy(), and memmove() in C
Writing The First C program
Infix to Prefix And Postfix in C
Getting Started with C
File Copying in C
Arrays sample program in C
Constants and escape sequences in C