Hi everyone,
I made a simple program that swaps two arrays of integers and I face some problems while looking at the result : it is different whether the swap function is called inside the main function or outside.
Here is a simple test :
[source lang="cpp"]#include <iostream>#define N 2void print( const std::string& label, const int* u){std::cout << label << "\t" << u;for ( int i=0 ; i<N ; i++ ) std::cout << "\t" << u[i];std::cout << std::endl;}void fswap(int* a, int* b){std::swap(a,b);}int main(){int* a = new int[N];int* b = new int[N];for (int i=0; i<N; ++i){ a[i] = i; b[i] = i+10;}// DIRECT SWAPprint( "a in", a);print( "b in", b);std::swap(a,b);print( "a out", a);print( "b out", b);// FUNCTION SWAPstd::cout << std::endl;print( "a in", a);print( "b in", b);fswap(a,b);print( "a out", a);print( "b out", b);delete [] a;delete [] b;return 0;}[/source]
Any idea ?!
Thx.
4 replies to this topic
Sponsor:
#2 Moderators - Reputation: 6672
Posted 21 November 2012 - 10:17 AM
fswap() takes the function parameters by value. Any change done on the parameters inside the function will not be reflected in the variables you passed to fswap(). One way to fix this is to change the parameter types from pointers to references to pointers. i.e. int *&
#3 Moderators - Reputation: 5061
Posted 21 November 2012 - 10:18 AM
C++ passes pointers by values, so fswap() doesn't affect the pointers in the caller. You could pass the pointers by reference:
void fswap(int *&a, int *&b)
{
std::swap(a, b);
}
Of course, this is a rather useless wrapper around std::swap, but it illustrates the point.
#5 Members - Reputation: 684
Posted 22 November 2012 - 04:05 AM
OP, if you thought you can swap by passing the pointer address, your code should look like
[source lang="cpp"]void fswap(int** a, int** b){std::swap(*a,*b);}fswap(&a, &b);[/source]
However, it's more common to swap two references to non-const, as code in rip-off's reply.
[source lang="cpp"]void fswap(int** a, int** b){std::swap(*a,*b);}fswap(&a, &b);[/source]
However, it's more common to swap two references to non-const, as code in rip-off's reply.
http://www.cpgf.org/
cpgf library -- free C++ open source library for reflection, serialization, script binding, callbacks, and meta data for OpenGL Box2D, SFML and Irrlicht.
v1.5.5 was released. Now supports tween and timeline for ease animation.






