Why does the pointer get its previous value returned from the function

guys how ptr gets its previous value? the code is simple, I just wonder why it does not save the address value that was assigned inside 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);


}

:

pointed memory value inside function: 710

pointer value inside function: 3405940

point memory value after exiting the function: 3

pointer value after exiting the function: 3406180

+3
source share
3 answers

You passed a pointer by value.

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

, , int*, ( "", , ++), int , , int. , .

( int, test. .)

+6

, , . , main. , .

+1

, , , .
, , ,

test(&ptr);

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

Alternatively, do not confuse with raw pointers. shared_ptr<>and &can be your friend!

+1
source

All Articles