.TH memchr() "" "" "String Function (libc)"
.PC "Search a region of memory for a character"
.B "#include <string.h>"
\fBchar *memchr(\fIregion\^\fB, \fIcharacter\^\fB, \fIn\^\fB)\fR
\fBchar *\fIregion\^\fB; int \fIcharacter\^\fB; unsigned int \fIn\^\fB;\fR
.PP
.II "region of memory, search for character"
.II "character, search for in region of memory"
.II "search for character in region of memory"
.B memchr()
searches the first
.I n
characters in
.I region
for
.IR character .
It returns the address of
.I character
if it is found, or NULL if it is not.
.PP
Unlike the string-search function
.BR strchr() ,
.B memchr()
searches a region of memory.
Therefore, it does not stop when it encounters a null character.
.SH 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.
.II "Floyd, Bob"
It uses an algorithm published by Bob Floyd in the
September 1987 \fICommunications of the ACM\fR.
.DM
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define DECK 52
.DE
.DM
main(argc, argv)
int argc; char *argv[];
{
	char deck[DECK], *fp;
	int  deckp, n, j, t;
.DE
.DM
	if(argc != 2 ||
	   52 < (n = atoi(argv[1])) ||
	   1 > n) {
	   	printf("usage: memchr n # where 0 < n < 53\en");
		exit(EXIT_FAILURE);
	}
.DE
.DM
	/* exercise rand() to make it more random */
	srand((unsigned int)time(NULL));
	for(j = 0; j < 100; j++)
		rand();
.DE
.DM
	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;
	}
.DE
.DM
	for(t = j = 0; j < deckp; j++) {
		div_t card;
.DE
.DM
		card = div(deck[j], 13);
		t += printf("%c%c  ",
			/* note useful string addressing */
			"A23456789TJQK"[card.rem],
			"HCDS"[card.quot]);
.DE
.DM
		if(t > 50) {
			t = 0;
			putchar('\en');
		}
	}
.DE
.DM
	putchar('\en');
	return(EXIT_SUCCESS);
}
.DE
.SH "See Also"
.Xr "libc," libc
.Xr "strchr()," strchr
.Xr "string.h" string.h
.br
\*(AS, \(sc7.11.5.1
