Search code examples
cfunctionpointersmemory-address

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

  • 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.