Recursion: reverse string in its position

recursion. I tested other online solutions and they seem to be almost identical to mine. The code should cancel the line (in its position), but it is not. For example, when you type st2 = "abcdefg", the output is an empty string. I was expecting st2 = "gfedcba". What am I missing?

#include <stdio.h>
#include <string.h>


void recurse_reverse(char s[], int sz)
{
    int i=0,j = sz -1;
    if(i<j)
    {
        swap(&s[i],&s[j]);
        recurse_reverse(s+1, sz-2);

    }
}


void swap( char* s1, char *s2)
{
    char tmp;
    tmp = *s1;
    *s1 = *s2;
    *s2 = tmp;
}


int main(void)
{
    char st1[9] = "abcdefg", st2[9];
    strcpy(st2,st1);
    recurse_reverse(st2,9);
    printf("s1 = %s\ns2 = %s",st1,st2);
    printf("\n" );
    return 0;
}
+4
source share
3 answers

You replace 2 null bytes at the end st1. Therefore, it st2starts with a zero byte, and therefore printf () does not print anything. You just need to correct your argument. Instead

recurse_reverse(st2,9);

do

recurse_reverse(st2,strlen(st1));

, , , st2 .

+5

printf . 9- , \0, \0 , .

hardcoding strlen .

1st char = a and 9th char is ▒
1st char = b and 9th char is
1st char = c and 9th char is g
1st char = d and 9th char is f
s1 = abcdefg
s2 = ▒

recurse_reverse(st2,strlen(st1));

1st char = a and 9th char 9th char is g
1st char = b and 9th char 9th char is f
1st char = c and 9th char 9th char is e
s1 = abcdefg
s2 = gfedcba
+3
#include <stdio.h>
#include <string.h>

void swap( char* s1, char *s2);

void recurse_reverse(char s[], int sz)
{
    int i=0,j = sz-1;
    if(i<j)
    {
        swap(&s[i],&s[j]);
        recurse_reverse(s+1, sz-2);

    }
}


void swap( char* s1, char *s2)
{
    char tmp;
    tmp = *s1;
    *s1 = *s2;
    *s2 = tmp;
}


int main(void)
{
    char st1[9] = "abcdefg", st2[9];
    int len=0;
    strcpy(st2,st1);
    len =strlen(st2);
    recurse_reverse(st2,len);
    printf("s1 = %s\ns2 = %s",st1,st2);
    printf("\n" );
    return 0;
}
+1
source

Source: https://habr.com/ru/post/1660923/


All Articles