'Twos pointers reflects the same value but with different address( C language)

I created a function to return the pointer as follows:

int* function(int cc){
    int* p;
    p=&cc; 
    return p;
}

int main(){
    int a;
    int *p1;
    a=10;
    p1=&a;
    printf("value for *p1 = %d\r\n",*p1);
    printf("value for *function  %d\r\n", *function(a));
    printf("pointer p1 = %p\r\n", p1);
    printf("pointer function= %p\r\n", function(a));

    return 0;
}

The console log is shown as follows:

value for *p1 = 10
value for *function  10
pointer p1 = 0x16d4bb1f8
pointer function= 0x16d4bb1dc

I really don't understand why two pointers could show the same value, but the address they stored are different.



Solution 1:[1]

do this

void function(int cc){
    int* p;
    p=&cc; 
   cc = 42; // just for fun
   printf("value of cc inside function  %d\r\n", cc);
  printf("value of &cc %p\r\n", &cc);
}

int main(){
    int a;
    int *p1;
    a=10;
    p1=&a;
    function(a);
    printf("value for *p1 = %d\r\n",*p1);
    printf("pointer p1 = %p\r\n", p1);
    return 0;
}

you will see that cc is a copy of a, if you change its value inside 'function' it does not change 'a'. You have found c's 'call by value' semantics. Meaning that variables are passed as copies to functions.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1