

memchr()                 String Function                 memchr()




Search a region of memory for a character

#include <string.h>
cchhaarr *mmeemmcchhrr(_r_e_g_i_o_n, _c_h_a_r_a_c_t_e_r, _n);
cchhaarr *_r_e_g_i_o_n; iinntt _c_h_a_r_a_c_t_e_r; uunnssiiggnneedd iinntt _n;

memchr searches  the first n characters  in region for character.
It returns the address of character if it is found, or NULL if it
is not.

Unlike  the  string-search  function  strchr, memchr  searches  a
region of memory.  Therefore, it does not stop when it encounters
a null character.

***** Example *****

The following  example deals a random hand of  cards from a stan-
dard deck of 52.  The  command line takes one argument, which in-
dicates the  size of the hand  you want dealt.  It  uses an algo-
rithm published by Bob Floyd in the September 1987 _C_o_m_m_u_n_i_c_a_t_i_o_n_s
_o_f _t_h_e _A_C_M.


#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define DECK 52



main(int argc, char *argv[])
{
        char deck[DECK], *fp;
        int  deckp, n, j, t;



        if(argc != 2 ||
           52 < (n = atoi(argv[1])) ||
           1 > n) {
                   printf("usage: memchr n # where 0 < n < 53\n");
                exit(EXIT_FAILURE);
        }



        /* exercise rand() to make it more random */
        srand((unsigned int)time(NULL));
        for(j = 0; j < 100; j++)
                rand();




COHERENT Lexicon                                           Page 1




memchr()                 String Function                 memchr()





        deckp = 0;
        /* Bob Floyd's algorithm */
        for(j = DECK - n; j < DECK; j++) {
                t = rand() % (j + 1);
                if((fp = memchr(deck, t, deckp)) != NULL)
                        *fp = (char)j;
                deck[deckp++] = (char)t;
        }



        for(t = j = 0; j < deckp; j++) {
                div_t card;



                card = div(deck[j], 13);
                t += printf("%c%c  ",
                        /* note useful string addressing */
                        "A23456789TJQK"[card.rem],
                        "HCDS"[card.quot]);



                if(t > 50) {
                        t = 0;
                        putchar('\n');
                }
        }



        putchar('\n');
        return(EXIT_SUCCESS);
}


***** See Also *****

strchr(), string functions, string.h















COHERENT Lexicon                                           Page 2


