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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…