Pointer Confusion: swap method in c

后端 未结 4 1034
情书的邮戳
情书的邮戳 2021-01-29 11:44
#include
void swap(int *a,int *b){
    int p=*b;
    *b=*a;
    *a=p;

    /*int *p=b;
    b=a;
    a=p;
    */
}

int main(){
    int a,b;
    scanf(\"%d         


        
4条回答
  •  时光说笑
    2021-01-29 12:28

    Assuming you meant

    void swap(int *a,int *b){
    int *p=b;
    b=a;
    a=p;
    }
    

    That code just swaps the value of the pointers in the swap() function. That won't swap the addresses around in main() because, as you said, "parameter int *a,int *b is local variable".

    When you call the function swap() like this

    swap(&a,&b);
    

    the addresses of a and b are passed and become local variables in the swap() function. You can't change the address of a or b - they have a location in memory.

    In the code that works

    void swap(int *a,int *b){
    int p=*b;
    *b=*a;
    *a=p;
    }
    

    you don't change the value of the pointers, you change the values in the memory the pointers point to, which is why that works.

    While C is pass-by-value, if you pass the address of something as the value a function can modify something outside its scope because you told the function where that variable is.

提交回复
热议问题