Using pointers within a swap function

I need help with using pointers to create a swap function. I am given a main
[code]
#include <iostream>
#include <fstream>
Last edited on
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?
dhayden whoops that was accident I changed it
Last edited on
Please post a compilable code.
coder777 my bad it compiles now
Last edited on
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.
Well, your swap(...) is not used but the std:: one.

That's the problem with using namespace std;
coder777 so what would i change?
jonin so make my own type? I cant use the int? do i just change my code to type * temp?
Last edited on
cali590 wrote:
so what would i change?
Add the prototype of your swap(...) function before main().
whoops how did i forget that thanks
Last edited on
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
Topic archived. No new replies allowed.