Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does pointer get its previous value returning from a function

Tags:

c++

pointers

guys how does the ptr get its previous value? code is simple, I just wondered why it doesn't store the address value that it's been assigned within the function.

#include<stdio.h>
#include<stdlib.h>
void test(int*);
int main( )
{
    int temp;
    int*ptr;   
    temp=3;
    ptr = &temp;
    test(ptr);


    printf("\nvalue of the pointed memory after exiting from the function:%d\n",*ptr);
    printf("\nvalue of the pointer after exiting from the function:%d\n",ptr);


system("pause ");
return 0;
} 


void test(int *tes){

    int temp2;        
    temp2=710;
    tes =&temp2;

    printf("\nvalue of the pointed memory inside the function%d\n",*tes);
    printf("\nvalue of the pointer inside the function%d\n",tes);


}

output is:

value of the pointed memory inside the function:710

value of the pointer inside the function:3405940

value of the pointed memory after exiting from the function:3

value of the pointer after exiting from the function:3406180

like image 714
markAnthopins Avatar asked May 24 '26 21:05

markAnthopins


2 Answers

You passed the pointer by value.

The pointer inside test is a copy of the pointer inside main. Any changes made to the copy do not affect the original.

This is potentially confusing because, by using an int*, you're passing a handle ("reference", though actually a reference is a separate thing that exists in C++) to an int and thus avoiding copies of that int. However, the pointer itself is an object in its own right, and you're passing that around by value.

(You're also attempting to point your pointer to an int that's local to the function test. Using it will be invalid.)

like image 95
Lightness Races in Orbit Avatar answered May 27 '26 11:05

Lightness Races in Orbit


The pointer is passed into the function by value, in other words a copy is made of it. In the function you change the copy, but that does not alter the value in main. If you wanted to change that, you would need to use a pointer to a pointer.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!