Search code examples
cpointersswap

confusion in passing a pointer to function in C


I was trying to understand pointers in C and wrote this code

#include <stdio.h>

int swap(int *fa,int *fb){
    int temp = *fa;
    *fa = *fb;
    *fb = temp;
}

int main(){
    int a=5,b=7;

    int *pa = &a;
    int *pb = &b;

    swap(pa,pb);

    printf("%d\n",*pa);
    printf("%d\n",*pb);

    printf("%d\n",a);
    printf("%d",b);
}

now the output(as expected) is

7
5
7
5

I am having a bit of understanding of what is happening but I have a confusion that

  1. right after I call the swap function, this happens
fa = pa // fa points to what pa points to which means a
fb = pb // fb points to what pb points to which means b
  1. we swap values of fa and fb, which in turn swap values of a and b, since pa and pb points to a and b they now point to these new values.

IS THIS WHAT IS HAPPENING

Or is it that fa and fb effect pa and pb first, which in turn effect a and b.


Solution

    1. right after I call the swap function, this happens
    fa = pa // fa points to what pa points to which means a
    fb = pb // fb points to what pb points to which means b
    

    If you mean after entering swap then yes. That is correct. Parameters are passed as a copy, which means inside that function fa and fb get a copy of pa and pb from the caller.

    1. we swap values of fa and fb, which in turn swap values of a and b, since pa and pb points to a and b they also point to these new values.

    No.fa and fb are not touched at all. They are dereferenced. This means, the address where they point to, is affected. You can use printf to print the content of those pointer variables. They will not change. Instead the content of a and b are changed.

    BTW: Your printf statements don't make much sense. You should print both before and after the function call to see any effect.