|
|
coherent
memchr() String Function memchr()
Search a region of memory for a character
#include <string.h>
cchhaarr *mmeemmcchhrr(_r_e_g_i_o_n, _c_h_a_r_a_c_t_e_r, _n);
cchhaarr *_r_e_g_i_o_n; iinntt _c_h_a_r_a_c_t_e_r; uunnssiiggnneedd iinntt _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
This archive runs on limited infrastructure. Preserving old code on modern bandwidth. Automated agents are requested to crawl responsibly.