Understanding simple pointers in C -


int main() {     int *p1,*p2;     int a;     p1=(int *)malloc(sizeof(int));     p2=(int *)malloc(sizeof(int));     p1=&a;     p2=p1;     a=10;     printf("\n%d\n",*p1);     printf("\n%d\n",*p2);     printf("\n%d\n",a);     return 0; } 

when remove lines p1=(int *)malloc(sizeof(int)); , p2=(int *)malloc(sizeof(int)); output doesn't change. can please explain why?

p1 = &a  

that throws away result of first malloc line, first malloc meaningless.

p2 = p1 

does same thing p2.

the space pointers of p1 , p2 allocated on stack, can assign them want without additional memory. need malloc if want assign integer them doesn't have memory allocated somewhere else already.

they both pointing memory allocated on stack a, , memory you've allocated on heap leaked , cannot recovered or released. can see true because when set 10, 3 print lines print 10.

because of this, program correct without 2 malloc lines.


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

javascript - jQuery .height() return 0 when visible but non-0 when hidden -