Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading