Home > Mobile >  Twos pointers reflects the same value but with different address( C language)
Twos pointers reflects the same value but with different address( C language)

Time:05-20

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.

CodePudding user response:

The variable you have passed in the function is done as a parameter (normal variable and not a pointer). If you really want the it should work like you expect then you should pass pointer instead of a normal int local variable.

Make these changes:

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;
}

This code works and shows the output that you expect... We did this as we don't want a new copy of the variable passed into the function. We want the same address and so we should pass variable address in the function.

CodePudding user response:

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 %d\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.

  • Related