This is a program to reverse the string in place. I have used pass by pointer. Interestingly I have changed the pointer in reverse function which is notable by seeing its output but the pointer which was passed in main function still points to the start of string. This is quite perplexing as I cannot figure out the cause for the same. Any help is appreciated.

#include <iostream>
#include <sstream>
using namespace std;

void reverse(char* str)
{
    cout<<str<<endl;
    char*end=str;
    if(str==0)
    {
        cout<<"null string detected"<<endl;
        return;
    }
    int length;

    while(*end)
    {end++;}
    end--;
    char temp;
//  char* begin=str;
    while(str<end)
    {
        temp=*str;
        *str++=*end;
        *end--=temp;
    }
    cout<<str<<endl;
}

int main()
{
    try
    {
        char* str=new char[100];    //char* str=new char[100000000000000000];
        cin>>str;
//      str=NULL;
        reverse(str);
        cout<<str<<endl;
        delete[] str;
    }
    catch(exception& e)
    {
        cout << "Standard exception: "<<e.what()<<endl;
    }
}

The pointer itself is passed by value, any changes you make to the pointer in reverse() is not visible to the pointer that was declared in main(). I ran your program and it looks like it works as expected.

If you want reverse() to change the pointer that's declared in main() then you have to pass it by address like this: reverse(&str) Then declare in in reverse like this: void reverse(char**str) But doing that will be disasterous because main() wouldn't be able to use the pointer any more and a memory leek will occur because main() can't delete[] it either.

Edited 3 Years Ago by Ancient Dragon

This was quite informative as I thought that any change in pointer was reflected in main(). One finaly query to sum up the issue. Is same behaviour expected in C?

I thought that any change in pointer was reflected in main().

You can pass a reference to achieve that behavior.

Is same behaviour expected in C?

Yes.

This question has already been answered. Start a new discussion instead.