• Advertisement
Sign in to follow this  

swapping issue

This topic is 1888 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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;

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;
b = 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
Advertisement
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
Sign in to follow this  

  • Advertisement