Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c - How does this reverseString algorithm work?

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...