~learax/csci112-2021-william-culhane

d49f4eb7eaa0bfdfdabfa116b5ebc9ac246d2c19 — William Culhane 3 years ago 77d4ca6 classwork12
classwork12: Refactor to avoid allocating tons of memory
1 files changed, 6 insertions(+), 19 deletions(-)

M classwork/classwork12/classwork12.c
M classwork/classwork12/classwork12.c => classwork/classwork12/classwork12.c +6 -19
@@ 7,34 7,21 @@
 * Wed Jun  2 12:19:42 PM MDT 2021
 */

unsigned char count_chars(char word[], unsigned int length) {
unsigned char count_chars(char word[]) {
  // Check if string is done
  if (word[0] == '\0') {
    return 0;
  } else if (length < 1) {
    // Length is too low; future allocations with lead to SEGFAULT
    // Must panic
    fprintf(stderr, "Input length longer than max!\n");
    exit(5);
  } else {
    // Create a new word with the first character removed
    char new_word[length - 1];
    for (unsigned char i = 0; i < length; i++) {
      // Check if last copied character was null
      if (word[i] == '\0') {
        break;
      } else {
        new_word[i] = word[i + 1];
      }
    }
    // Count the characters in the word with a character missing
    return (count_chars(new_word, length - 1) + 1);
    return (count_chars(&word[1]) + 1);
  }
}

int main(void) {
  // Read max number of characters
  unsigned int max_length = 20;
  // The program will happily run over the max and starting writing
  // into adjacent memory, but this seems to work alright
  unsigned int max_length = 20; // Defaults to 20
  printf("Enter a max word length> ");
  scanf("%u", &max_length);



@@ 44,7 31,7 @@ int main(void) {
  scanf("%s", word);

  // Output calculation and delivery
  unsigned char length = count_chars(word, max_length);
  unsigned char length = count_chars(word);
  printf("Length: %hhu\n", length);

  return (0);