I want this function to add a point to the beginning of the linked list:
void addPoint(Point *head, int x, int y, SDL_bool dir) {
Point *p = malloc(sizeof *p);
p->x = x;
p->y = y;
p->dir = dir;
p->next = head;
head = p;
}
The head is initialized earlier like so:
Point *down = NULL;
Afterwards I call the function like so:
addPoint(&down, x * grid_cell_width, (y - 1) * grid_cell_height, SDL_FALSE);
Unfortunately this does not work as After after the call the head is still NULL.
CodePudding user response:
You are passing a pointer to head
, meaning you are passing a copy of the address of head
to function addPoint
. In the line where you are changing the value of head
you are actually modifying the local pointer. To change that, you need to pass a pointer to a pointer, like so:
void addPoint(Point **head, int x, int y, SDL_bool dir) {
Point *p = malloc(sizeof(Point));
p->x = x;
p->y = y;
p->dir = dir;
p->next = head;
*head = p;
}
CodePudding user response:
Try something like:
void addPoint(Point **head, int x, int y, SDL_bool dir) {
Point p = malloc(sizeof(*p));
p->x = x;
p->y = y;
p->dir = dir;
p->next = head;
*head = p;
}
In C there is no pass-by-reference mechanism per se, you just pass pointers to arguments instead (in this case, a pointer to a pointer). But those pointers are still just values, so a change to them is not visible outside of the function. What will be visible is a change to the value that the pointer points to. That's why you need to assign your p pointer to the location that the pointer head points to, hence you need to dereference it with (*) operator first.
CodePudding user response:
You got this part right:
addPoint(&down,...);
but the type of the expression &down
is Point **
, not Point *
, so you need to change the definition of addPoint
to
void addPoint(Point **head, int x, int y, SDL_bool dir) {
...
p->next = *head;
*head = p;
}
With this code, you have the following relationships:
head == &down // Point ** == Point **
*head == down // Point * == Point *
So in the addPoint
function, writing to *head
is the same as writing to down
.