2

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; } 
1
  • For problem #1 try std::swap then you don't have to worry about all of this. Pointer to pointer instead of reference to pointer just makes using swappointers clunky. Commented Aug 28, 2014 at 2:31

3 Answers 3

7

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I don't think Problem 1 is impossible. How about by passing **ptrX and **ptrY in the function? I got that somewhat hint. Thank you :)
@Asad: That generally falls under the category of "passing by reference" (In C, it's the only way to pass by reference, in C++ you have the choice of using a pointer or a reference)
Thank you for telling that, Ben.
2
  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.

1 Comment

You cleared the 2nd problem. Thanks. I don't know about that "auto". Moreover, I can not use that.
1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.