C++ Swapping Pointers

后端 未结 5 1283
天涯浪人
天涯浪人 2020-12-05 11:21

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 lea

5条回答
  •  时光取名叫无心
    2020-12-05 12:11

    You passed references to your values, which are not pointers. So, the compiler creates temporary (int*)'s and passes those to the function.

    Think about what p and q are: they are variables, which means they are slots allocated somewhere in memory (on the stack, but that's not important here). In what sense can you talk about "swapping the pointers"? It's not like you can swap the addresses of the slots.

    What you can do is swap the value of two containers that hold the actual addresses - and those are pointers.

    If you want to swap pointers, you have to create pointer variables, and pass those to the function.

    Like this:

    int p = 7;
    int q = 9;
    
    int *pptr = &p;
    int *qptr = &q;
    swap(pptr, qptr);
    cout << "p = " << *pptr << "q= " << *qptr << endl;
    return 0;
    

提交回复
热议问题