1

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?

5
  • What do you expect recursion(ptr++); to do? Commented Nov 20, 2021 at 11:42
  • To increase the pointer and go to the next char. It actually works while I don't use recursion. Commented Nov 20, 2021 at 11:42
  • 6
    Do you know the very important difference between ptr++ and ++ptr? Commented Nov 20, 2021 at 11:43
  • 1
    The format string "%c%" is invalid. I assume you mean "%c". Commented Nov 20, 2021 at 11:46
  • Thank you for very constructive answers! Now I know what I did wrong. Commented Nov 20, 2021 at 11:48

2 Answers 2

3

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()
Sign up to request clarification or add additional context in comments.

Comments

0

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.