c - Dynamically allocating in main() VS in a funtion -
int foo(int *p){ p = malloc(sizeof(int)); *p = 20; } int main(){ int a; int *x; x = &a; foo(x); printf("%d \n", a); return 0; }
so i'm trying point @ a
, set value of x
pointing 20. whenever allocate pointer in function random number being printed. know why happens compared allocating in main()?
you don't want allocate in foo function @ all. doing:
void foo(int p) { p = 2; printf("%d\n", p); } int main() { int a=1; foo(a); return 0; }
and asking why didn't print 1. answer is, you're writing on pointer a, no longer have pointer when *p = 20;
.
Comments
Post a Comment