1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
#include "clog.h"


// BUGGY!!!!

bool count_consecutive_chars(char ch, char** a_pos, int* a_num_occurrences) {
    *a_num_occurrences = 0;

    while(**a_pos == ch) {
        /* *a_num_occurrences++;   // BAD!!! */
        /* *a_pos++;               // BAD!!! */
        *a_num_occurrences += 1;  // GOOD
        *a_pos += 1;  // GOOD
        /* (*a_num_occurrences)++;  // ALSO OKAY */
        /* (*a_pos)++;              // ALSO OKAY */
    }

    return (*a_num_occurrences >= 1 ? true : false);  // true if we found any; false otherwise
}
// AUTOCOMPLETE: Ctrl-P

int main(int argc, char* argv[]) {
    int num_occurrences;
    char* input = "aaabbcccc"; // address of the first character of this string (on the data segment)
    char* pos = input;         // address of the character to look at next

    // Count 'a'
    // At this point, *a_pos refers to the first character of the string (on the data segment),
    // which is an 'a'.
    char char_to_search_for = 'a';
    bool found_any = count_consecutive_chars(char_to_search_for, &pos, &num_occurrences);
    log_char(char_to_search_for);
    log_bool(found_any);
    log_int(num_occurrences);
    printf("\n");

    // Count 'b'
    // At this point, *a_pos refers to the first 'b' in the string (on the data segment).
    char_to_search_for = 'b';
    found_any = count_consecutive_chars(char_to_search_for, &pos, &num_occurrences);
    log_char(char_to_search_for);
    log_bool(found_any);
    log_int(num_occurrences);
    printf("\n");

    // At any given point, *a_pos refers to the next character we want to look at.

    // Count 'c'
    char_to_search_for = 'c';
    found_any = count_consecutive_chars(char_to_search_for, &pos, &num_occurrences);
    log_char(char_to_search_for);
    log_bool(found_any);
    log_int(num_occurrences);
    printf("\n");

    // Count 'X'
    char_to_search_for = 'X';
    found_any = count_consecutive_chars(char_to_search_for, &pos, &num_occurrences);
    log_char(char_to_search_for);
    log_bool(found_any);
    log_int(num_occurrences);
    printf("\n");

    return EXIT_SUCCESS;
}
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */

© Copyright 2022 Alexander J. Quinn         This content is protected and may not be shared, uploaded, or distributed.