Reputation: 63
I have been programming a simple game in C to learn programming, but I found an error in my code when I work with a linked list.
Here is my struct
:
typedef struct ListShoots * ListShoots;
struct ListShoots{
Shoot d;
ListShoots next;
};
And my functions about 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 I call the function Shoots_Shoot
in the main (at first, ld = NULL
), I get the output: ld = NULL
and ld = NULL (again)
too. Why? There should be just the first printf
, I think, because at first the line while(ld!=NULL) ld = ld->next
does nothing.
The weird thing is: If I remove the line ld = aux;
, the output is okay, just: ld = NULL
.
EDIT: The problem is: aux
and ld
are pointing at the same memory because of aux = ld
. So if I reserve memory for ld
, immediately aux
changes and will be not pointing to NULL
, right?
Upvotes: 1
Views: 83
Reputation: 1079
- aux and ld are pointing to the same memory here:
ListShoots aux = ld;
- But now if this loop is done at least once they not are pointing to the same memory:
while(ld!=NULL) ld = ld->next;
- Now ld points to another space memory due to malloc, while aux still points to the same place:
ld = Shoots_Create(x,y);
- And you remember that you said that aux was pointing NULL at the beginning? Well, now ld are pointing to the same memory that aux again. It means NULL:
ld = aux;
Aux is always the same value (the value of ld when the method starts), so both conditionals test always print the same.
Upvotes: 0
Reputation: 21351
In regard to the specific problem you are describing look at your function
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");
}
The first line stores the passed in value of ld
in aux
variable. You then print if ld
is null.
Later you change ld
ld = Shoots_Create(x,y);
but immediately after (before the printf) you do so again back to its original value with the next line
ld = aux;
so essentially both conditionals are testing the same value (the value of ld
passed to the function). This is why when you remove the line
ld = aux;
it works - because then you don't change the return value of Shoots_Create(x,y)
function
Upvotes: 0
Reputation: 1679
... I get the output: "ld = NULL" and "ld = NULL(again)" too. ¿Why?
Because of
ListShoots aux = ld;
/* ... */
ld = aux;
You are restoring the original value of ld
, which apparently is NULL
, since you are getting
ld = NULL
from
if(ld==NULL) printf("ld = NULL\n");
Upvotes: 2