XraySensei
XraySensei

Reputation: 192

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?

Upvotes: 1

Views: 470

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 310950

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()

Upvotes: 3

OrenIshShalom
OrenIshShalom

Reputation: 7102

The increment of ptr occurs only after the recursive call for recursion. A simple fix should be:

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


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

Upvotes: 0

Related Questions