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
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.)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With