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\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?

Answers


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.


Need Your Help

strange and alien memory behavior

ios memory memory-leaks memory-management

in my project i created a class viewTransistion

How can I execute multiple, simultaneous jquery effects?

jquery animation effects jquery-animate effect

I am animating some error/validation elements on a page. I want them to bounce and be highlighted, but at the same time if possible. Here's what I'm currently doing:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.