
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
        "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- MyFirstUnitAd -->
<ins class="adsbygoogle"
     style="display:inline-block;width:970px;height:250px"
     data-ad-client="ca-pub-5778386704669218"
     data-ad-slot="1503492166"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <link rel="stylesheet" type="text/css" href="../../../style.css" title="style" />
    <link rel="stylesheet" type="text/css" href="../style.css" title="style" />
    <meta http-equiv="content-type" content="text/html;charset=utf-8" />

    <title>bsearch.3p - Linux manual page</title>
</head>

<body>

<div class="page-top"><a id="top_of_page"></a></div>
<!--%%%TOP_BAR%%%-->
    <div class="nav-bar">
        <table class="nav-table">
            <tr>
                <td class="nav-cell">
                    <p class="nav-text">
                        <a href="http://man7.org/index.html">man7.org</a> &gt; Linux &gt; <a href="../index.html">man-pages</a>
                    </p>
                </td>
                <td class="training-cell">
                    <p class="training-text"><a class="training-link" href="http://man7.org/training/">Linux/UNIX system programming training</a></p>
                </td>
            </tr>
        </table>
    </div>

<hr class="nav-end" />

<!--%%%PAGE_START%%%-->


<table class="sec-table">
<tr>
    <td>
        <p class="section-dir">
<a href="bsearch.3p.html#PROLOG">PROLOG</a> | <a href="bsearch.3p.html#NAME">NAME</a> | <a href="bsearch.3p.html#SYNOPSIS">SYNOPSIS</a> | <a href="bsearch.3p.html#DESCRIPTION">DESCRIPTION</a> | <a href="bsearch.3p.html#RETURN_VALUE">RETURN&nbsp;VALUE</a> | <a href="bsearch.3p.html#ERRORS">ERRORS</a> | <a href="bsearch.3p.html#EXAMPLES">EXAMPLES</a> | <a href="bsearch.3p.html#APPLICATION_USAGE">APPLICATION&nbsp;USAGE</a> | <a href="bsearch.3p.html#RATIONALE">RATIONALE</a> | <a href="bsearch.3p.html#FUTURE_DIRECTIONS">FUTURE&nbsp;DIRECTIONS</a> | <a href="bsearch.3p.html#SEE_ALSO">SEE&nbsp;ALSO</a> | <a href="bsearch.3p.html#COPYRIGHT">COPYRIGHT</a>
        </p>
    </td>
    <td class="search-box">
        <div class="man-search-box">

            <form method="get" action="http://www.google.com/search">
                <fieldset class="man-search">
                    <input type="text" name="q" size="10" maxlength="255" value="" />
                    <input type="hidden" name="sitesearch" value="man7.org/linux/man-pages" />
                    <input type="submit" name="sa" value="Search online pages" />
                </fieldset>
            </form>

        </div>
    </td>
    <td> </td>
</tr>
</table>

<pre>
<span class="headline">BSEARCH(3P)               POSIX Programmer's Manual              BSEARCH(3P)</span>
</pre>
<h2><a id="PROLOG" href="bsearch.3p.html#PROLOG"></a>PROLOG  &nbsp; &nbsp; &nbsp; &nbsp; <a href="bsearch.3p.html#top_of_page"><span class="top-link">top</span></a></h2><pre>
       This manual page is part of the POSIX Programmer's Manual.  The Linux
       implementation of this interface may differ (consult the
       corresponding Linux manual page for details of Linux behavior), or
       the interface may not be implemented on Linux.
</pre>
<h2><a id="NAME" href="bsearch.3p.html#NAME"></a>NAME  &nbsp; &nbsp; &nbsp; &nbsp; <a href="bsearch.3p.html#top_of_page"><span class="top-link">top</span></a></h2><pre>
       bsearch — binary search a sorted table
</pre>
<h2><a id="SYNOPSIS" href="bsearch.3p.html#SYNOPSIS"></a>SYNOPSIS  &nbsp; &nbsp; &nbsp; &nbsp; <a href="bsearch.3p.html#top_of_page"><span class="top-link">top</span></a></h2><pre>
       #include &lt;stdlib.h&gt;

       void *bsearch(const void *<i>key</i>, const void *<i>base</i>, size_t <i>nel</i>,
           size_t <i>width</i>, int (*<i>compar</i>)(const void *, const void *));
</pre>
<h2><a id="DESCRIPTION" href="bsearch.3p.html#DESCRIPTION"></a>DESCRIPTION  &nbsp; &nbsp; &nbsp; &nbsp; <a href="bsearch.3p.html#top_of_page"><span class="top-link">top</span></a></h2><pre>
       The functionality described on this reference page is aligned with
       the ISO C standard. Any conflict between the requirements described
       here and the ISO C standard is unintentional. This volume of
       POSIX.1‐2008 defers to the ISO C standard.

       The <i>bsearch</i>() function shall search an array of <i>nel</i> objects, the
       initial element of which is pointed to by <i>base</i>, for an element that
       matches the object pointed to by <i>key</i>.  The size of each element in
       the array is specified by <i>width</i>.  If the <i>nel</i> argument has the value
       zero, the comparison function pointed to by <i>compar</i> shall not be
       called and no match shall be found.

       The comparison function pointed to by <i>compar</i> shall be called with two
       arguments that point to the <i>key</i> object and to an array element, in
       that order.

       The application shall ensure that the comparison function pointed to
       by <i>compar</i> does not alter the contents of the array. The
       implementation may reorder elements of the array between calls to the
       comparison function, but shall not alter the contents of any
       individual element.

       The implementation shall ensure that the first argument is always a
       pointer to the key.

       When the same objects (consisting of width bytes, irrespective of
       their current positions in the array) are passed more than once to
       the comparison function, the results shall be consistent with one
       another.  That is, the same object shall always compare the same way
       with the key.

       The application shall ensure that the function returns an integer
       less than, equal to, or greater than 0 if the <i>key</i> object is
       considered, respectively, to be less than, to match, or to be greater
       than the array element. The application shall ensure that the array
       consists of all the elements that compare less than, all the elements
       that compare equal to, and all the elements that compare greater than
       the <i>key</i> object, in that order.
</pre>
<h2><a id="RETURN_VALUE" href="bsearch.3p.html#RETURN_VALUE"></a>RETURN VALUE  &nbsp; &nbsp; &nbsp; &nbsp; <a href="bsearch.3p.html#top_of_page"><span class="top-link">top</span></a></h2><pre>
       The <i>bsearch</i>() function shall return a pointer to a matching member of
       the array, or a null pointer if no match is found. If two or more
       members compare equal, which member is returned is unspecified.
</pre>
<h2><a id="ERRORS" href="bsearch.3p.html#ERRORS"></a>ERRORS  &nbsp; &nbsp; &nbsp; &nbsp; <a href="bsearch.3p.html#top_of_page"><span class="top-link">top</span></a></h2><pre>
       No errors are defined.

       <i>The following sections are informative.</i>
</pre>
<h2><a id="EXAMPLES" href="bsearch.3p.html#EXAMPLES"></a>EXAMPLES  &nbsp; &nbsp; &nbsp; &nbsp; <a href="bsearch.3p.html#top_of_page"><span class="top-link">top</span></a></h2><pre>
       The example below searches a table containing pointers to nodes
       consisting of a string and its length. The table is ordered
       alphabetically on the string in the node pointed to by each entry.

       The code fragment below reads in strings and either finds the
       corresponding node and prints out the string and its length, or
       prints an error message.

           <b>#include &lt;stdio.h&gt;</b>
           <b>#include &lt;stdlib.h&gt;</b>
           <b>#include &lt;string.h&gt;</b>

           #define TABSIZE    1000

           struct node {                  /* These are stored in the table. */
               char *string;
               int length;
           };
           struct node table[TABSIZE];    /* Table to be searched. */
               .
               .
               .
           {
               struct node *node_ptr, node;
               /* Routine to compare 2 nodes. */
               int node_compare(const void *, const void *);
               .
               .
               .
               while (scanf("%ms", &amp;node.string) != EOF) {
                   node_ptr = (struct node *)bsearch((void *)(&amp;node),
                          (void *)table, TABSIZE,
                          sizeof(struct node), node_compare);
                   if (node_ptr != NULL) {
                       (void)printf("string = %20s, length = %d\n",
                           node_ptr-&gt;string, node_ptr-&gt;length);
                   } else {
                       (void)printf("not found: %s\n", node.string);
                   }
                   free(node.string);
               }
           }
           /*
               This routine compares two nodes based on an
               alphabetical ordering of the string field.
           */
           int
           node_compare(const void *node1, const void *node2)
           {
               return strcoll(((const struct node *)node1)-&gt;string,
                   ((const struct node *)node2)-&gt;string);
           }
</pre>
<h2><a id="APPLICATION_USAGE" href="bsearch.3p.html#APPLICATION_USAGE"></a>APPLICATION USAGE  &nbsp; &nbsp; &nbsp; &nbsp; <a href="bsearch.3p.html#top_of_page"><span class="top-link">top</span></a></h2><pre>
       The pointers to the key and the element at the base of the table
       should be of type pointer-to-element.

       The comparison function need not compare every byte, so arbitrary
       data may be contained in the elements in addition to the values being
       compared.

       In practice, the array is usually sorted according to the comparison
       function.
</pre>
<h2><a id="RATIONALE" href="bsearch.3p.html#RATIONALE"></a>RATIONALE  &nbsp; &nbsp; &nbsp; &nbsp; <a href="bsearch.3p.html#top_of_page"><span class="top-link">top</span></a></h2><pre>
       The requirement that the second argument (hereafter referred to as <i>p</i>)
       to the comparison function is a pointer to an element of the array
       implies that for every call all of the following expressions are non-
       zero:

           <b>((char *)p − (char *(base) % width == 0</b>
           <b>(char *)p &gt;= (char *)base</b>
           <b>(char *)p &lt; (char *)base + nel * width</b>
</pre>
<h2><a id="FUTURE_DIRECTIONS" href="bsearch.3p.html#FUTURE_DIRECTIONS"></a>FUTURE DIRECTIONS  &nbsp; &nbsp; &nbsp; &nbsp; <a href="bsearch.3p.html#top_of_page"><span class="top-link">top</span></a></h2><pre>
       None.
</pre>
<h2><a id="SEE_ALSO" href="bsearch.3p.html#SEE_ALSO"></a>SEE ALSO  &nbsp; &nbsp; &nbsp; &nbsp; <a href="bsearch.3p.html#top_of_page"><span class="top-link">top</span></a></h2><pre>
       <a href="hcreate.3p.html">hcreate(3p)</a>, <a href="lsearch.3p.html">lsearch(3p)</a>, <a href="qsort.3p.html">qsort(3p)</a>, <a href="tdelete.3p.html">tdelete(3p)</a>

       The Base Definitions volume of POSIX.1‐2008, <a href="../man0/stdlib.h.0p.html">stdlib.h(0p)</a>
</pre>
<h2><a id="COPYRIGHT" href="bsearch.3p.html#COPYRIGHT"></a>COPYRIGHT  &nbsp; &nbsp; &nbsp; &nbsp; <a href="bsearch.3p.html#top_of_page"><span class="top-link">top</span></a></h2><pre>
       Portions of this text are reprinted and reproduced in electronic form
       from IEEE Std 1003.1, 2013 Edition, Standard for Information
       Technology -- Portable Operating System Interface (POSIX), The Open
       Group Base Specifications Issue 7, Copyright (C) 2013 by the
       Institute of Electrical and Electronics Engineers, Inc and The Open
       Group.  (This is POSIX.1-2008 with the 2013 Technical Corrigendum 1
       applied.) In the event of any discrepancy between this version and
       the original IEEE and The Open Group Standard, the original IEEE and
       The Open Group Standard is the referee document. The original
       Standard can be obtained online at <a href="http://www.unix.org/online.html">http://www.unix.org/online.html</a> .

       Any typographical or formatting errors that appear in this page are
       most likely to have been introduced during the conversion of the
       source files to man page format. To report such errors, see
       <a href="https://www.kernel.org/doc/man-pages/reporting_bugs.html">https://www.kernel.org/doc/man-pages/reporting_bugs.html</a> .

<span class="footline">IEEE/The Open Group                 2013                         BSEARCH(3P)</span>
</pre>

<hr class="end-man-text" />
<p>Pages that refer to this page: 
    <a href="../man0/stdlib.h.0p.html">stdlib.h(0p)</a>,&nbsp; 
    <a href="hcreate.3p.html">hcreate(3p)</a>
</p>
<hr/>

 
<hr class="start-footer" />

<div class="footer"> 

<table class="colophon-table">
    <tr>
    <td class="pub-info">
        <p>
            HTML rendering created 2018-02-02
            by <a href="http://man7.org/mtk/index.html">Michael Kerrisk</a>, 
            author of 
            <a href="http://man7.org/tlpi/"><em>The Linux Programming Interface</em></a>, 
            maintainer of the 
            <a href="https://www.kernel.org/doc/man-pages/">Linux <em>man-pages</em> project</a>.
        </p>
        <p>
            For details of in-depth
            <strong>Linux/UNIX system programming training courses</strong>
            that I teach, look <a href="http://man7.org/training/">here</a>.
        </p>
        <p>
            Hosting by <a href="http://www.jambit.com/index_en.html">jambit GmbH</a>.
        </p>
        <p>
            <a href="http://validator.w3.org/check?uri=referer">
            <img src="http://www.w3.org/Icons/valid-xhtml11"
                alt="Valid XHTML 1.1" height="31" width="88" />
            </a>
        </p>
    </td>
    <td class="colophon-divider">
    </td>
    <td class="tlpi-cover">
        <a href="http://man7.org/tlpi/"><img src="../../../tlpi/cover/TLPI-front-cover-vsmall.png" alt="Cover of TLPI" /></a>
    </td>
    </tr>
</table>

</div>

<hr class="end-footer" />



<!--BEGIN-SITETRACKING-->
<!-- SITETRACKING.man7.org_linux_man-pages -->

<!-- Start of StatCounter Code (xhtml) -->

<script type="text/javascript">
//<![CDATA[
var sc_project=7422636; 
var sc_invisible=1; 
var sc_security="9b6714ff"; 
//]]>
</script>
<script type="text/javascript"
src="http://www.statcounter.com/counter/counter_xhtml.js"></script>
<noscript><div class="statcounter"><a title="website
statistics" href="http://statcounter.com/"
class="statcounter"><img class="statcounter"
src="http://c.statcounter.com/7422636/0/9b6714ff/1/"
alt="website statistics" /></a></div></noscript>

<!-- End of StatCounter Code -->


<!-- Start of Google Analytics Code -->

<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-9830363-8']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>

<!-- End of Google Analytics Code -->

<!--END-SITETRACKING-->

</body>
</html>
