markAnthopins
markAnthopins

Reputation: 237

why does pointer get its previous value returning from a function

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

Upvotes: 3

Views: 1532

Answers (3)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385144

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

Upvotes: 6

Greg Domjan
Greg Domjan

Reputation: 14105

In case the other answers describing the issue are not sufficient.
The code you want so you can change the value is along these lines

test(&ptr);

void test(int **tes){
    int *temp2 = new int;
    *tes =&temp2;
}

Alternativly, don't mess with raw pointers. shared_ptr<> and & can be your friend!

Upvotes: 1

user2100815
user2100815

Reputation:

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.

Upvotes: 1

Related Questions