Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
356 views
in Technique[技术] by (71.8m points)

recursion - Explanation of Output For Simple Reverse String Algorithm in C

This is just a simple program that reverses a string (shown below).

I understand how to actual recursion part of this works, I'm just a little confused about the output I am getting when putting print statements in specific places.

#include <stdio.h>

char *reverse_string(char *x, int start, int end) {
    
    char ch;
    
    if (start < end) {
        ch = *(x + start);
        *(x + start) = *(x + end);
        *(x + end) = ch;
        printf("Before: %s
", x);
        reverse_string(x, ++start, --end);
        printf("After: %s
", x);
    }
    return x;
    
}

int main() {
    
    char testString[] = "ABCDEF";
    char *newString[7];
    
    printf("Original: %s

", testString);
    
    *newString = reverse_string(testString, 0, 5);
    
    printf("
Reversed: %s
", *newString);
    
    return 0;
}
  

When I traced this program with pen and paper, I predicted that the output was going to look like this:

Original: ABCDEF

Before: FBCDEA
Before: FECDBA
Before: FEDCBA
After: FEDCBA
After: FEDCBA
After: FEDCBA

Reversed: FEDCBA

However, the actual output I am getting is:

Original: ABCDEF

Before: FBCDEA
Before: FECDBA
Before: FEDCBA
After: FEDCBA
After: FEDCBA
After: FEDCBA

Reversed: FEDCBA

It might be a little hard to see but the first two "Before" print statements between what I predicted and what actually happened are different.

I'm just a little confused as to why are they all the same??

Any explanation for this would be greatly appreciated!! Thanks!!

question from:https://stackoverflow.com/questions/65837775/explanation-of-output-for-simple-reverse-string-algorithm-in-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Nevermind I didn't realize the outputs were the same. Just checked my program and I did have them copied right. I guess I was right about my prediction of the output after all LOL. Sorry for the inconvenience everyone.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...