Monday, March 28, 2011

Reverse String

#include <iostream>
using namespace std;

//This function accepts a string and returns the reversed string to the caller function.
char* revStr(char *str)
{
        //checking for null pointer
        if(str == 0)
                return 0;

        //get the length of the string we received.
        int len = strlen (str);

         /**    Allocate memory in heap of the same data type.
                It'll be wrong to declare memory in stack e.g. char str1[len]
                because we are returning address to the caller function.
                The locally allocated memory will be destroyed once we return to the caller.
                so using new operator or malloc function
         **/
        char *str1 = new char[len];

        //We can't change the original string so copy the source string
        //to the newly allocated space for local manipulation
        strcpy(str1, str);

        // Loop: half of the string length
        for (int i=0, j = len-1 ; i<len/2; i++, j--)
        {
                // the standard swapping logic
                char t;
                t = str1[i];
                str1[i] = str1[j];
                str1[j] = t;
        }
        //returning the address of the memory in heap, which persistes even after retrun.
        //However str1 pointer will no longer be accessible after return.
        return str1;

}

//One of the calller function
char* test ()
{
        char *p = "abc";
        return revStr(p);

}

// main function
int main()
{
        char str[14];
        cout<<"Enter a string to reverse : ";
        cin>>str;

        // Testing multiple assignment operator
        char *str1, *str2;
        str1 = revStr(str);
        cout<<"The reversed string :"<<str1<<endl;
        cout<<"The original string :"<< str<<endl;
        str2 = test();
        cout<<"The function call...."<<str2<<endl;

        //Explicitly deallocating memory allocated in heap in revStr()
        delete str1;
        delete str2;

}