I'm trying to write a function that takes a string and determines the length of said string using recursion (this is a requirement for the assignment). The assignment uses c strings, so that is why I'm checking for the null byte.
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <cstring>
usingnamespace std;
constint MAX_INPUT_LINE_LENGTH = 100;
int str_length_r ( constchar str[] )
{
int length = 1;
if ( str[0] == '\0')
return 0;
// This is the base case. If the 0th element in the array passed into the function is the null byte, then 0 is returned.
elsereturn length + str_length_r(str[1]);
// This is the recursive function call. str[1] is passed in order to make the array one element smaller with each recursive call.
}
So I'm passing str[1] to try and make the string incrementally smaller until the null byte is reached, at which point the "length" value from each recursive call is summed.
BUT this is the error I'm getting at line 20:
invalid conversion from 'const char' to 'const char*'
So the compiler is telling me that I'm trying to pass a character (str[1]) into an array. How can I make the string smaller with each recursive call? That is, how can I eliminate the [0] element at each recursive call so that the string is one element smaller each time? Apparently passing str[1] does not work.
The error is exactly what it says, invalid conversion from 'const char' to 'const char*'. You are passing in a constant char (str[1]) when the function wants a pointer. Use str[1]*.