Search code examples
crecursionc-stringspost-increment

Recursive function for outputing string


I have a following code:

#include <stdio.h>
void recursion(char *ptr) {
    if(*ptr!='J') recursion(ptr++);
    printf("%c",*ptr);
}


void main() {
    char v[]="!zenaJ";
    char *ptr=v;
    recursion(ptr);
}

I would like to return Janez! trough the recursive function. I don't have any errors when compiling. When I run the program I get an error "Segmentation fault (core dumped)". What am I doing wrong?


Solution

  • You are passing recursively the same pointer

    if(*ptr!='J') recursion(ptr++);
    

    because the value of the post-increment expression ptr++ is the value of the pointer before its incrementing.

    The function written in C can look the following way

    void recursion( const char *ptr ) 
    {
        if ( *ptr )
        {
            recursion( ptr + 1 );    
            putchar( *ptr );
        }
    }
    

    In C++ the function can look the following way

    std::ostream & recursion( const char *ptr, std::ostream &os = std::cout ) 
    {
        if ( *ptr )
        {
            recursion( ptr + 1 );    
            os << *ptr;
        }
    
        return os;
    }
    

    Pay attention to that according to the C Standard the function main without parameters shall be declared like

    int main( void )
    

    and in C++ it can be declared like

    int main()