i am trying to swap a pair of pointer values. i can do this if i pass the the pointers in by value but is they a way i can do this when i pass the values in by reference.
Actually, I guess he didn't need that! I tried out the function after I posted. Opps! All of this pointer stuff sometimes throws me for a loop still, but the above makes sense to me now.
Hi BoulderBum, as I found out a few weeks ago myself, you get the smileys from the link below called "Emoticons/SMileys" next the Email ntoification check box. There's a ton of different smileys in there that you can use.
As the template function I listed - recall that a pointer is simply an address in memory (a numeric value). Its actually no different than passing in a couple of 'ints' and swapping them!
May the force be with you!
programmer (prog'ram'er), n A hot-headed, anorak wearing, pimple-faced computer geek.
however i still have the problem
the swap function works well with ints as when you declare the variable temp it gets its own memory space and the assignment operator "temp = a" merely copies the contents of "a" into "temp's" memory address. with pointers however, when you do the assignment "temp = a" , temp will now point to what ever "a" points to - so if you change "a" you will also change temp - so temp cant be used as a buffer in this way which is the problem im having - i dont know if there is a solution ...is they way i can store the memory address as a int like you say then re-assign the pointer address with the int variables?
thanks for your time on this
jim
Jimberger, both my function and Gednick's swapped pointer values successfully for me. When you have an integer "a" and assign a pointer ("ptr1" to it, the pointer points to "a"'s memory address. When you define a second pointer ("ptr2" and have an assignment like ptr2 = ptr1, then ptr2 points to "a" not ptr1. You can change the address ptr1 points to, and ptr2 will not be affected.
Try it out! I used cout << ptr1 << ' ' << ptr2 << endl; before and after the switch to check the address each pointer was assigned to.
If you cout your pointers, make sure they're not char pointers unless you like seeing random strings of characters.
Also, there's no need to write a new swap function; the STL already has one. Just #include <algorithm>.
There's also an iter_swap. It swaps what each iterator points to (and pointers are considered iterators). I'm not sure if this is the behavior you're looking for, or if you just want swap.
Finally, in your initial post, you say yo were able to swap when you pass in by value... I'm not sure how you would have accomplished this. Is it possible you're getting the correct results with the code that's been posted, but are comparing them to the results of your "swap by value," which is actually incorrect?
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.