View more

View more

View more

### Image of the Day Submit

IOTD | Top Screenshots

### The latest, straight to your Inbox.

Subscribe to GameDev.net Direct to receive the latest updates and exclusive content.

# swapping issue

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

4 replies to this topic

### #1TGE  Members

Posted 21 November 2012 - 09:57 AM

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.

### #2SiCrane  Moderators

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 *&

### #3rip-off  Moderators

Posted 21 November 2012 - 10:18 AM

POPULAR

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.

### #4AlexB.hpp  Members

Posted 21 November 2012 - 12:20 PM

Edited by AlexB.hpp, 21 November 2012 - 12:21 PM.

C x 2 C x o C x C f nice C x C s C x C c

### #5wqking  Members

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.

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.

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.