COHERENT manpages

This page displays the COHERENT manpage for memchr() [Search a region of memory for a character].

List of available manpages
Index


memchr() -- String Function (libc)

Search a region of memory for a character
#include <string.h>
char *memchr(region, character, n)
char *region; int character; unsigned int 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 standard deck of
52.  The command  line takes one argument, which indicates  the size of the
hand you  want dealt.  It uses  an algorithm published by  Bob Floyd in the
September 1987 Communications of the ACM.

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

main(argc, argv)
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();

    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

libc,
strchr(),
string.h
ANSI Standard, §7.11.5.1