Getting an error for a recursive function call with a string

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.

Here is my code (just the recursive function):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>     
#include <fstream>      
#include <stdlib.h>     
#include <cstring>    


using namespace std;

const int MAX_INPUT_LINE_LENGTH = 100;

int str_length_r ( const char 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.

  else
    return 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.


Last edited on
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]*.
Ok, so when I change to

 
return length + str_length_r(str[1]*);


I get another error

expected primary-expression before ')' token

Excuse me, *str[1].

iSoBad
Thanks Intrexa. However now I'm getting this error

invalid type argument 'unary *'

Is this due to how the function is called in main()?
Does anyone know how to fix this error?
Topic archived. No new replies allowed.