Thread: Using bsearch to search for a string in an array of strings.

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Mar 2020
    Posts
    10

    Using bsearch to search for a string in an array of strings.

    I have an array of strings called tab.
    I want to search for an array in it with the function bsearch() provided by <stdlib.h>.
    But I think I am doing something wrong, since it cannot find "delta".
    Is my code wrong?

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    #define LEN(x) (sizeof (x) / sizeof (x[0]))
    
    char *tab[] = {
        "alfa",
        "beta",
        "delta",
        "epsilon",
        "gama",
        "zeta",
    };
    
    int
    main(int argc, char *argv[])
    {
        char **t;
        char s[] = "delta";
    
        t = bsearch(&s, tab, LEN(tab), sizeof *tab, (int(*)(const void *, const void *)) strcmp);
        if (t != NULL)
            printf("%s\n", *t);
    
        return EXIT_SUCCESS;
    }
    Last edited by felixthunder; 04-02-2020 at 10:05 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. bsearch in array of pointers to struct
    By redgr in forum C Programming
    Replies: 3
    Last Post: 03-19-2015, 08:36 AM
  2. Bsearch() isn't finding an integer key in my array.
    By MilleniumFalcon in forum C++ Programming
    Replies: 20
    Last Post: 03-22-2014, 04:26 PM
  3. Replies: 5
    Last Post: 10-13-2012, 11:43 PM
  4. Sorting Strings: Binary Search for string
    By alexhollis in forum C Programming
    Replies: 9
    Last Post: 03-15-2012, 12:30 PM
  5. search numbers in an inputed string [array of strings]
    By zattara13 in forum C Programming
    Replies: 1
    Last Post: 03-28-2008, 06:11 AM

Tags for this Thread