Swap


Dear fellows ve a look of this swap function n tell me why this line( swap(&x[j],&x[j+1]);) is passing the addresses of variables instead of values?N the result of this program shows an extra line of 1(like 1 1 1 1 1 1 ) at the end of the result ..from where this line comes???



#include <iostream.h>
#include <stdlib.h>

void swap(int *, int *) ;

main(){

int x [] = {1,3,5,7,9,2,4,6,8,10}; // x[0]=1
int i, j, tmp, swaps;



for(i = 0; i < 10; i ++){

swaps = 0;

for(j = 0; j < 10; j ++){

// compare two values and interchange if needed
if ( x[j] > x[j+1]) // j=0 x[0] > x[1]
{
swaps++;

swap(&x[j],&x[j+1]);
}

}

for (j=0; j<10; j++){
cout << x[j] << '\t';

if (swaps == 0) break;

}
}
int stop ;
cin>>stop;
}


void swap(int *x, int *y){

int tmp;
if(*x > *y){

tmp = *x;
*x = *y;
*y = tmp;

}//if

}
Last edited on
Putting "&" before a variable will return the variable's pointer.
And if you just pass values to "swap", the changes that you do in the "swap" function (swapping the variables) will be just "local", so they won't affect the variables you have in "main".
e.g.
1
2
3
4
5
6
7
8
9
10
11
12
void Swap(int a, int b)
{
int temp = a;
a = b;
b = temp;
}
int main()
{
int a = 3, b = 5;
swap(a,b);
cout<<a<<" "<<b<<endl;
}

If you put a breakpoint in Swap, you'll find A is 5 and B is 3.
But in main, A will be 3.
And B will be 5.
But from where a line of 1's comes at the end of the result???
closed account (zb0S216C)
swap(&x[j],&x[j+1]); (sic)

No. What you're doing here is passing the address of the specified items of x. In C++, memory addresses are a completely different type.

The std::swap( )[1, Link] function is a template function. The function requires two arguments, both of which are references to type T. With references, you don't have to explicitly pass the address of the variables you wish to swap.

References:
[1]http://www.cplusplus.com/reference/algorithm/swap/


Wazzak
Last edited on
A reference IS an address.
Passing a reference means passing an address.
Topic archived. No new replies allowed.