Sign in to follow this  
TGE

swapping issue

Recommended Posts

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 2
void 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 SWAP
print( "a in", a);
print( "b in", b);

std::swap(a,b);

print( "a out", a);
print( "b out", b);

// FUNCTION SWAP

std::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.

Share this post


Link to post
Share on other sites
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 *&

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this