C++ recursion counting char

-1

I need to write a recursive function that accepts the string s and character c and returns the number of occurrences of the character c in the string s.

The function signature is int occur(char *s,char c);.

I have to use pointers..

I get an exception:

Unhandled exception at 0x00FF1E49 in HW4_307950675_317226223_Q2.exe: 0xC00000FD: Stack overflow (parameters: 0x00000001, 0x00D22FDC).

This is my code:

#include <iostream>
using namespace std;
#include <string.h>


int occur(char* s, char c) {
    if (&s == 0) {
        return 0;
    }

    if (*(s+1) == 'c') {
        return occur(s+1, c) + 1;   
    }
    else {
        return occur(s + 1, c);
   }
}

int main() {
    char c = 'c';
    char s[] = { 'c','c','c','c','c' };
    cout << occur(s,c);
}
c++
recursion
stack-overflow
asked on Stack Overflow Dec 25, 2019 by Omer Tesler • edited Dec 25, 2019 by Martin Bonner supports Monica

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0