@@ 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);