@@ 1,6 1,5 @@
#include <stdio.h>
-
-#define MAX_CHARACTERS 20
+#include <stdlib.h>
/*
* William Culhane
@@ 8,14 7,19 @@
* Wed Jun 2 12:19:42 PM MDT 2021
*/
-unsigned char count_chars(char word[MAX_CHARACTERS + 1]) {
+unsigned char count_chars(char word[], unsigned int length) {
// 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[MAX_CHARACTERS];
- for (unsigned char i = 0; i < MAX_CHARACTERS; i++) {
+ 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;
@@ 24,16 28,23 @@ unsigned char count_chars(char word[MAX_CHARACTERS + 1]) {
}
}
// Count the characters in the word with a character missing
- return (count_chars(new_word) + 1);
+ return (count_chars(new_word, length - 1) + 1);
}
}
int main(void) {
- char word[MAX_CHARACTERS + 1];
- printf("Enter a word (max length %i characters)> ", MAX_CHARACTERS);
+ // Read max number of characters
+ unsigned int max_length = 20;
+ printf("Enter a max word length> ");
+ scanf("%u", &max_length);
+
+ // Read word itself
+ char word[max_length + 1];
+ printf("Enter a word (max length %i characters)> ", max_length);
scanf("%s", word);
- unsigned char length = count_chars(word);
+ // Output calculation and delivery
+ unsigned char length = count_chars(word, max_length);
printf("Length: %hhu\n", length);
return (0);