c - Memory in a linked list -
i have been programming simple game in c learn programming, found error in code when work linked list.
here struct
:
typedef struct listshoots * listshoots; struct listshoots{ shoot d; listshoots next; };
and functions memory:
listshoots shoots_create(int x, int y){ listshoots ld = malloc(sizeof(struct listshoots)); ld->d.alto = 10; ld->d.x = x; ld->d.y = y; ld->d.v = 6; ld->next = null; return ld; } void shoots_shoot(listshoots ld, int x, int y){ listshoots aux = ld; if(ld==null) printf("ld = null\n"); while(ld!=null) ld = ld->next; ld = shoots_create(x,y); ld = aux; if(ld==null) printf("ld = null (again)\n"); }
when call function shoots_shoot
in main (at first, ld = null
), output: ld = null
, ld = null (again)
too. why? there should first printf
, think, because @ first line while(ld!=null) ld = ld->next
nothing.
the weird thing is: if remove line ld = aux;
, output okay, just: ld = null
.
edit: problem is: aux
, ld
pointing @ same memory because of aux = ld
. if reserve memory ld
, aux
changes , not pointing null
, right?
... output: "ld = null" , "ld = null(again)" too. ¿why?
because of
listshoots aux = ld; /* ... */ ld = aux;
you restoring original value of ld
, apparently null
, since getting
ld = null
from
if(ld==null) printf("ld = null\n");
Comments
Post a Comment