Using pointers within a swap function

Feb 3, 2020 at 10:08pm
I need help with using pointers to create a swap function. I am given a main
[code]
#include <iostream>
#include <fstream>
Last edited on Feb 4, 2020 at 5:13am
Feb 3, 2020 at 10:24pm
cout<<"*n1 is: "<<*x<<", *n2 is: "<<*y<<endl;
When you claim to print *n1, you actually print *x and when you claim to print *n2, you actually print *y. What do x and y have to do with anything here?
Feb 3, 2020 at 10:26pm
dhayden whoops that was accident I changed it
Last edited on Feb 3, 2020 at 10:29pm
Feb 3, 2020 at 10:27pm
Please post a compilable code.
Feb 3, 2020 at 10:28pm
coder777 my bad it compiles now
Last edited on Feb 3, 2020 at 10:30pm
Feb 3, 2020 at 10:37pm
pointer swap works just like any swap.

type * tmp = a;
a = b;
b = tmp;

where a and b are type*.

the key here is that a pointer is just an int, while type could be some fat class, so this is more efficient if the type is nontrivial.
Feb 3, 2020 at 10:39pm
Well, your swap(...) is not used but the std:: one.

That's the problem with using namespace std;
Feb 3, 2020 at 10:44pm
coder777 so what would i change?
Feb 3, 2020 at 10:46pm
jonin so make my own type? I cant use the int? do i just change my code to type * temp?
Last edited on Feb 3, 2020 at 10:48pm
Feb 3, 2020 at 10:51pm
cali590 wrote:
so what would i change?
Add the prototype of your swap(...) function before main().
Feb 3, 2020 at 11:02pm
whoops how did i forget that thanks
Last edited on Feb 3, 2020 at 11:14pm
Feb 4, 2020 at 12:42am
a struct or class is a user defined type, as is a typedef/using etc.
yes, you can use ints, but swapping ints is the same as pointers, no real gain there; the only point is if you had pointers already and were just in the middle of something.

so what would i change?
Add the prototype of your swap(...) function before main().

change the name of it to myfreakingswap so it does not collide with anything? Try hard not to use names that are part of the namespaces or common items at least. Also you can look at using less than std, and pull in only what you need eg using std::cout

Your swap is an integer swap that happens to take pointers to the ints. Mine is a pointer swap, that swaps the pointers instead of the items. Its an important difference.
Last edited on Feb 4, 2020 at 12:46am
Topic archived. No new replies allowed.