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 | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
#include "clog.h"
// REDUNDANT
// BUGGY
bool count_consecutive_chars(char ch, int* a_num_occurrences, char** a_pos) {
*a_num_occurrences = 0;
if(**a_pos != ch) { // if the character at *a_pos is NOT ch, then we return false
return false; // indicates that the character 'ch' was not found.
}
else {
while(**a_pos == ch) {
*a_num_occurrences += 1; // BUG!!!! 'num_occurrences' was never initialized.
*a_pos += 1; // Set this aside for now.
}
return true;
}
}
int main(int argc, char* argv[]) {
char* input = "aaabbcccc"; // address of the first character in the string (on the data segment)
char* pos = input; // address of the next character to look at; like a "cursor"
int num_occurrences; // will be initialized by count_consecutive_chars(…)
char char_to_search_for = 'a';
bool found_any = count_consecutive_chars(char_to_search_for, &num_occurrences, &pos);
log_char(char_to_search_for);
log_int(num_occurrences);
log_bool(found_any);
printf("\n");
return EXIT_SUCCESS;
}
// *a_num_occurrences refers to the value at (address) a_num_occurrences.
//
// int* is a type for variables that contain the address of an int.
/* 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.