Need help with this recursion problem!!

So I am trying to write a recursive function in which it takes in an array of character( with a null terminating at the end ) and a target character. It will return the number of character in the array that match the target character.
And this is what I have so far and it keep saying "overflow" in my compiler...
Can someone please help me identify the problem?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
int match( char* arry, const char target ){
	if ( *arry == '\0' ){
		return 0;
	}
	else if ( *arry == target ){
		return 1+match( arry++, target );
	}
	else{
		return match(arry++,target );
	}
}

int main(){
	char* arry = "erte";
	char target = 'e';
	int a;
	a = match( arry, target );
	cout << a;
	system("pause");
}
Last edited on
To make an array of chars, you should write: char arry[] = "erte";. Also, I don't think that you can increment arry with just ++. I can't think of any good way to do this problem at the moment, so I suggest passing in an int initialized at 0 in the main function, and using that to mark where you are in "erte". Also, I suggest that you use a string instead of a char, I really don't always like working with chars.
Pointers can be incremented with ++. Read up about pointer arithmatic.

As you're using post-increment, you're calling the function recursively with the same value (the increment is done after the call). Swapping to pre-increment should fix the problem. Or use arry+1 instead (I would prob. do the latter myself)
Last edited on
Topic archived. No new replies allowed.