Asad
Asad

Reputation: 21

Confusion about Pointers C++

Task: I want to swap pointers without reference passing the pointers in the function.

Problem 1: The following code does the job but I think its swapping the "data" instead of swapping the "pointers".

void swappointers(char *ptrX, char *ptrY)
{
   char dummy;
   dummy = *ptrX;
   *ptrX = *ptrY;    //LINE
   *ptrY = dummy;
}

Problem 2: How the commented line is working? *ptrX means that ptrX is being de-referenced(accessing the value the pointer is directing to). Similar is the case with *ptrY. But why the value being directed by ptrX is being changed here? I mean its actually looking like this:

ValueofX = ValueofY

Thank you :)

Edit:

Solved the first problem.

void swappointers(char **ptrX, char **ptrY)
{
   char *dummy = nullptr;
   dummy = *ptrX;
   *ptrX = *ptrY;
   *ptrY = dummy;
}

Upvotes: 2

Views: 148

Answers (3)

GingerPlusPlus
GingerPlusPlus

Reputation: 5606

  1. template<typename T>
    void swap(T &a, T &b){
        T backup=a;
        a=b;
        b=backup;
    }
    
  2. *ptrX = *ptrY; means variable, to which points ptrX, have to have same value as variable to which points ptrY.

Upvotes: 2

Jacques de Hooge
Jacques de Hooge

Reputation: 6990

About your commented line:

*ptrX = *ptrY;    //LINE

In plain English it means:

Put the value of the memory location pointed to by ptrY into the memory location pointed to by ptrX.

Upvotes: 1

Ben Voigt
Ben Voigt

Reputation: 283614

I think its swapping the "data" instead of swapping the "pointers".

You are correct.

I want to swap pointers without reference passing the pointers in the function.

That's impossible. Unless you pass by reference, changes made inside the function will not be seen by the caller.

Upvotes: 7

Related Questions