Am I handling the pointer the wrong way? I want to update the value of a variable by passing it's address to the function.
void func(int *p){
int x = 3;
p = &x;
}
int main(){
int y = 0;
func(&y);
printf("\n Value = %d",y);
}
I get the following output:
Value = 0 Exited: ExitFailure 11
You must dereference the pointer to replace the value on which the pointer points.
See:
#include <stdio.h>
void func(int *p){
int x = 3;
*p = x;
}
int main(){
int y = 0;
func(&y);
printf("\n Value = %d",y);
return 0;
}
To remove the exit failure add the return 0; statement into the main function.
See running example: http://ideone.com/rO8Gua
void func(int *p){
*p = 3;
}
You were setting p
to the address of a local variable x
. First, setting the value of p
doesn't change the value of y
(the function just receives a copy of the address of y
, and even if you change that, you are not going to change y
).
Second, x is a local variable, so you cannot use it's content after the function func
is terminated.
Third, you cannot change the address of y
in this way because it is a local variable. You would need to declare it as a pointer.
You can refer to content of memory referred to by p by using *p. So, p =&x;
will change p not the content of memory referred to by p. You should have used, *p = x
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