Swapping pointer in C [duplicate]

走远了吗. 提交于 2019-12-02 11:31:53

a and d are not swapped as the function mystery() doesn’t change values, but pointers which are local to the function.

Yes, you are right. Function mystery is not swapping values. It is just swapping the pointer ptra and ptrb to location pointed by ptrb and ptra respectively.

                        a
                 +--------------+
                 |              |
ptra ----------> |    2016      |
                 |              |
                 +--------------+



                        b
                 +--------------+
                 |              |
ptrb ----------> |      0       |
                 |              |
                 +--------------+

After executing statements

temp = ptrb;  
ptrb =ptra; 
ptra = temp;    

                        a
                 +--------------+
                 |              |
ptra -----+      |    2016      |
        +------> |              |
        | |      +--------------+
        | |
        | |
        | |
        | |             b
        | |      +--------------+
        | |      |              |
ptrb ---+ +----> |      0       |
                 |              |
                 +--------------+
dbush

In C, functions always pass by value. So the pointer swapping you're doing has no effect outside the function because you're only changing local values.

Instead of swapping the pointers, you need to swap what they point to, i.e. you need to dereference them:

void mystery (int *ptra, int *ptrb) {  
     const int temp = *ptrb;
     *ptrb = *ptra; 
     *ptra = temp; 
} 

Your temporary needs to be an int not an int*:

int temp = *ptrb;

Then you need to defererence the pointers: *ptrb = *ptra; etc.

All you're currently doing is swapping the pointers in the function, and this will not be reflected in the function caller.

The function mystery() does virtually nothing, and a compiler eliminated almost all of the function via optimization and left only ret.

demo on Compiler Explorer

First thing to note: mystery woks on copy of pointers being passeed to it. This has huge implications, most of them being you are not changing original pointers when you assign to pointers ptra, ptrb in your mystery.

void mystery (int *ptra, int *ptrb) {  
     int *temp; 
     temp = ptrb;  
     ptrb =ptra; 
     ptra = temp; 
}

Second thing: you are indeed assigning pointers to pointers, not values of what pointers points to. And given first mistake, the world outside of the mystery sees no changes at all.

Solution:

Dereference pointers to change values they are pointing to.

void
mystery (int *ptra, int *ptrb)
{  
    const int tmp;

    tmp = *ptrb;
    *ptrb = *ptra; 
    *ptra = tmp; 
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!