каждый раз, когда вы запускаете этот код, baby dijkstra плачет :)
1
2
3
4 #include <ctype.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
8
9
10 size_t bytewise_pop_count(
11 unsigned char * bp, size_t l
12 ) {
13 if ( (bp) && (l) ) {
14 return bytewise_pop_count(bp+1, l-1) + (bp[0] ? 1 : 0);
15 }
16 return 0;
17 }
18
19 void mercilessly_complement_bytes(
20 unsigned char * bp, size_t l
21 ) {
22 /*
23 transform
24 0 -> 1
25 !0 -> 0
26 */
27 if ( (bp) && (l) ) {
28 bp[0] = bp[0] ? 0 : 1;
29 mercilessly_complement_bytes(bp+1, l-1);
30 }
31 }
32
33 void xor_bytes(
34 unsigned char * bp1, unsigned char * bp2, size_t l
35 ) {
36 /* stores result in bp2 */
37 if ( (bp1) && (bp2) && (l) ) {
38 bp2[0] ^= bp1[0];
39 xor_bytes(bp1+1, bp2+1, l-1);
40 }
41 }
42
43
44 int main(int argc, char * * argv) {
45 char c;
46 size_t count;
47 size_t l;
48 char * string;
49 char * t;
50
51 if (argc < 3) {
52 fprintf(stderr,
53 "\n"
54 "==> not enough arguments -- need char and string\n"
55 "\n"
56 );
57 return EXIT_FAILURE;
58 }
59
60 c = argv[1][0];
61 string = argv[2];
62
63 if ( l = strlen(string) ) {
64 t = malloc(l);
65 memset(t, c, l);
66 xor_bytes(string, t, l);
67 mercilessly_complement_bytes(t, l);
68 count = bytewise_pop_count(t, l);
69 free(t);
70 } else {
71 count = 0;
72 }
73
74 if ( isprint(c) ) {
75 printf(
76 "\n"
77 "==> occurences of char ``%c'' in string ``%s'': %zu\n"
78 "\n"
79 , c, string ? string : "<NULL>", count
80 );
81 } else {
82 printf(
83 "\n"
84 "==> occurences of char ``%hhu'' in string ``%s'': %zu\n"
85 "\n"
86 , c, string ? string : "<NULL>", count
87 );
88 }
89 return EXIT_SUCCESS;
90 }