I have seen this algorithm to reverse a string online, and I have some doubts about it which I will specify at the end of the code:
void reverseString(char *original_string)
{
char *end = original_string;
char tmp;
if(original_string) {
while(*end) {
++end;
}
--end;
while (original_string < end) {
tmp = *original_string;
*original_string++ = *end;
*end-- = tmp;
}
}
//This line doesn't have the complete reversed string. Why?
printf("%s
", original_string);
}
1) In the while loop...Why do we compare two pointers? How do we know that the value is going to be bigger or smaller?? Those are just pointers, right?
2) Why don't we return anything? Where is the reversed string? If we are impyling that the reversed string is in the original_string, shouldn't we have used a pointer to pointer so that the effects are in the outter scope?
3) If I do the following:
char test[] = "hello";
reverseString(test);
printf("%s
", test);
I can see the "olleh". However, if I do printf("%s
", original_string);
at the very last line of the function reverseString, I just get "leh". Why is that?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…