I\'m working on a function to swap pointers and I can\'t figure out why this isn\'t working. When I print out r and s in the swap function the values are swapped, which lea
You passed references to your values, which are not pointers. So, the compiler creates temporary (int*)
's and passes those to the function.
Think about what p
and q
are: they are variables, which means they are slots allocated somewhere in memory (on the stack, but that's not important here). In what sense can you talk about "swapping the pointers"? It's not like you can swap the addresses of the slots.
What you can do is swap the value of two containers that hold the actual addresses - and those are pointers.
If you want to swap pointers, you have to create pointer variables, and pass those to the function.
Like this:
int p = 7;
int q = 9;
int *pptr = &p;
int *qptr = &q;
swap(pptr, qptr);
cout << "p = " << *pptr << "q= " << *qptr << endl;
return 0;