Swap() methods

What is the difference between these two swap() methods:

1. void swap(int **a, int **b)
{
int *temp;
temp = *a;
*a = *b;
*b = temp;
}

2. void swap(int* a, int* b)
{
int* temp;
temp = a;
a = b;
b = temp;
}
#2 doesn't do anything.
What do you mean doesn't do anything. the program compiles the same way. The only thing that i see is that #2 doesn't use dereferencing in its method.
closed account (1vRz3TCk)
#2 works on the copies of the pointers and does not effect the data 'outside' of the function.

this swaps the contents of what a and b point to.
1
2
3
4
5
6
7
void swap(int* a, int* b)
{
    int temp;
    temp = *a;
    *a = *b;
    *b = temp;
}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>

void swap1(int **a,int **b){
    int *temp;
    temp=*a;
    *a=*b;
    *b=temp;
}

void swap2(int* a, int* b){
    int* temp;
    temp = a;
    a = b;
    b = temp;
}

int main(){
    int a=10,
        b=20,
        *c=&a,
        *d=&b;
    std::cout <<*c<<"; "<<*d<<std::endl;
    swap1(&c,&d);
    std::cout <<*c<<"; "<<*d<<std::endl;
    swap2(c,d);
    std::cout <<*c<<"; "<<*d<<std::endl;
}
Topic archived. No new replies allowed.