How does this reverseString algorithm work?

╄→尐↘猪︶ㄣ 提交于 2019-12-13 02:51:29

问题


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\n", 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\n", test);

I can see the "olleh". However, if I do printf("%s\n", original_string); at the very last line of the function reverseString, I just get "leh". Why is that?


回答1:


You have the two pointers pointing to the beginning and the end of the section left to be reversed. On each step you swap the characters pointed to by these pointers and then decrease the string that is left to be reversed from both directions - beginning and end. Comparing the pointers has the following meaning - until the beginning of the interval is not after the end of the interval, we still have an interval to reverse. Hope that makes sense.

You don't need to return anything - the string is reversed in place so the argument is in and out at the same time.

3) In the function you take a copy of the pointer to the string, that you modify during its execution, so as the pointer is modified by the last line it will no longer point to the beginning of the string, but to the middle, where it is left at at the end.



来源:https://stackoverflow.com/questions/14485585/how-does-this-reversestring-algorithm-work

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!