|
|
1.1 ! root 1: ! 2: ! 3: memchr() String Function memchr() ! 4: ! 5: ! 6: ! 7: ! 8: Search a region of memory for a character ! 9: ! 10: #include <string.h> ! 11: cchhaarr *mmeemmcchhrr(_r_e_g_i_o_n, _c_h_a_r_a_c_t_e_r, _n); ! 12: cchhaarr *_r_e_g_i_o_n; iinntt _c_h_a_r_a_c_t_e_r; uunnssiiggnneedd iinntt _n; ! 13: ! 14: memchr searches the first n characters in region for character. ! 15: It returns the address of character if it is found, or NULL if it ! 16: is not. ! 17: ! 18: Unlike the string-search function strchr, memchr searches a ! 19: region of memory. Therefore, it does not stop when it encounters ! 20: a null character. ! 21: ! 22: ***** Example ***** ! 23: ! 24: The following example deals a random hand of cards from a stan- ! 25: dard deck of 52. The command line takes one argument, which in- ! 26: dicates the size of the hand you want dealt. It uses an algo- ! 27: rithm published by Bob Floyd in the September 1987 _C_o_m_m_u_n_i_c_a_t_i_o_n_s ! 28: _o_f _t_h_e _A_C_M. ! 29: ! 30: ! 31: #include <stddef.h> ! 32: #include <stdio.h> ! 33: #include <stdlib.h> ! 34: #include <string.h> ! 35: #include <time.h> ! 36: #define DECK 52 ! 37: ! 38: ! 39: ! 40: main(int argc, char *argv[]) ! 41: { ! 42: char deck[DECK], *fp; ! 43: int deckp, n, j, t; ! 44: ! 45: ! 46: ! 47: if(argc != 2 || ! 48: 52 < (n = atoi(argv[1])) || ! 49: 1 > n) { ! 50: printf("usage: memchr n # where 0 < n < 53\n"); ! 51: exit(EXIT_FAILURE); ! 52: } ! 53: ! 54: ! 55: ! 56: /* exercise rand() to make it more random */ ! 57: srand((unsigned int)time(NULL)); ! 58: for(j = 0; j < 100; j++) ! 59: rand(); ! 60: ! 61: ! 62: ! 63: ! 64: COHERENT Lexicon Page 1 ! 65: ! 66: ! 67: ! 68: ! 69: memchr() String Function memchr() ! 70: ! 71: ! 72: ! 73: ! 74: ! 75: deckp = 0; ! 76: /* Bob Floyd's algorithm */ ! 77: for(j = DECK - n; j < DECK; j++) { ! 78: t = rand() % (j + 1); ! 79: if((fp = memchr(deck, t, deckp)) != NULL) ! 80: *fp = (char)j; ! 81: deck[deckp++] = (char)t; ! 82: } ! 83: ! 84: ! 85: ! 86: for(t = j = 0; j < deckp; j++) { ! 87: div_t card; ! 88: ! 89: ! 90: ! 91: card = div(deck[j], 13); ! 92: t += printf("%c%c ", ! 93: /* note useful string addressing */ ! 94: "A23456789TJQK"[card.rem], ! 95: "HCDS"[card.quot]); ! 96: ! 97: ! 98: ! 99: if(t > 50) { ! 100: t = 0; ! 101: putchar('\n'); ! 102: } ! 103: } ! 104: ! 105: ! 106: ! 107: putchar('\n'); ! 108: return(EXIT_SUCCESS); ! 109: } ! 110: ! 111: ! 112: ***** See Also ***** ! 113: ! 114: strchr(), string functions, string.h ! 115: ! 116: ! 117: ! 118: ! 119: ! 120: ! 121: ! 122: ! 123: ! 124: ! 125: ! 126: ! 127: ! 128: ! 129: ! 130: COHERENT Lexicon Page 2 ! 131: ! 132:
This archive runs on limited infrastructure. Preserving old code on modern bandwidth. Automated agents are requested to crawl responsibly.