HiveBrain v1.2.0
Get Started
← Back to all entries
patterncMinor

Reversing a string in place without using iteration in C

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
withoutplaceiterationreversingusingstring

Problem

This is function for reversing a string in C using recursive calls:

#include 
#include 

void revert(char* left, char* right) { // Should I pass char* like I'm doing now or are char** a better idea?
    if(left == right) return;

    char *ll = left; char* rr = right;

    char tmp = right[0];
    right[0] = left[0];
    left[0] = tmp;
    revert(++ll,--rr);
}

int main() {
    char rev_string[] = "Some teststring";
    printf("%s\n", rev_string);
    revert(&rev_string[0],&rev_string[strlen(rev_string)-1]);//rev_string[strlen(rev_string)-1]);
    printf("%s\n", rev_string); 
    return 0;
}


Can it be simplified? Can anything be written better?

Solution

-
There is a bug. Some teststring contains an odd number of characters, therefore a left == right condition is eventually hit. For an even-length string, it would never be satisfied. You should test for left

-
There is absolutely no need to reassign
left, right to ll, rr. revert(++left, --right)` works as good.

To clear the possible confusion (see comments) this is what I meant:

if (left < right) {
    swap_values(left, right);
    revert(++left, --right);
}

Code Snippets

if (left < right) {
    swap_values(left, right);
    revert(++left, --right);
}

Context

StackExchange Code Review Q#70530, answer score: 2

Revisions (0)

No revisions yet.