Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Swapping Pointers

Tags:

c++

pointers

I'm working on a function to swap pointers and I can't figure out why this isn't working. When I print out r and s in the swap function the values are swapped, which leads me to believe I'm manipulating a copy of which I don't understand because I pass by reference of p and q.

void swap(int *r, int *s)
{
    int *pSwap = r;
    r = s;
    s = pSwap;
    return;
}

int main()
{
    int p = 7;
    int q = 9;  
    swap(&p, &q);
    cout << "p = " << p << "q= " << q << endl;
    return 0;
}

Prints: p = 7q = 9

like image 850
M K Avatar asked Mar 28 '13 01:03

M K


2 Answers

Inside your swap function, you are just changing the direction of pointers, i.e., change the objects the pointer points to (here, specifically it is the address of the objects p and q). the objects pointed by the pointer are not changed at all.

You can use std::swap directly. Or code your swap function like the following:

void swap(int *r, int *s)
{
   int temp = *r;
   *r = *s;
   *s = temp;
   return;
} 
like image 59
taocp Avatar answered Nov 15 '22 03:11

taocp


The accepted answer by taocp doesn't quite swap pointers either. The following is the correct way to swap pointers.

void swap(int **r, int **s)
{
    int *pSwap = *r;
    *r = *s;
    *s = pSwap;
}

int main()
{
    int *p = new int(7);
    int *q = new int(9);

    cout << "p = " << std::hex << p << std::endl;
    cout << "q = " << std::hex << q << std::endl << std::endl;

    swap(&p, &q);

    cout << "p = " << std::hex << p << std::endl;
    cout << "q = " << std::hex << q << std::endl << std::endl;

    cout << "p = " << *p << " q= " << *q << endl;
    return 0;
}

Output on my machine:

p = 0x2bf6440
q = 0x2bf6460

p = 0x2bf6460
q = 0x2bf6440

p = 9 q= 7
like image 42
zar Avatar answered Nov 15 '22 04:11

zar