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; }
std::swapthen you don't have to worry about all of this. Pointer to pointer instead of reference to pointer just makes usingswappointersclunky.