Pointer Confusion: swap method in c

后端 未结 4 1046
情书的邮戳
情书的邮戳 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:07

    In the second method, you use the local variable that is limited in the scope of the function swap. So, the variable a or b in main function is different with variable a or b that is defined as the argument in the swap function.

    When you use the pointer, the swap function will change the value that is pointed by the pointer (it means that the function change the value at the address of a and b that are declared in the main function).

提交回复
热议问题