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;
    }
}

Recommended Answers

All 4 Replies

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.

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?

yes

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.