I expected the output of the following program to to be 5 , but the compiler is displaying 20 . Can someone please explain why?
#include <stdio.h>
int a=5;
change1(int *p);
int main(void)
{
int x=20,*ptr=&x;
change1(ptr);
printf("%d ",*ptr);
return 0;
}
change1(int *p)
{
p=&a;
}
You're passing a pointer, which causes the function to make a copy. In order to change it you have to pass a pointer to a pointer.
If you want to modify a pointer, you need to pass a pointer to pointer:
change1(&ptr);
and then:
void change1(int **p)
{
*p = &a;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.