W ramach nauki, piszę własną implementację listy jednokierunkowej, chciałbym się dowiedzieć co jest nie tak z poniższym kodem. Przy okazji zaznaczę, że zależy mi możliwie jak najprostszym/najlepszym rozwiązaniem.
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int val;
struct node *next;
} node;
void insert(node**, int);
void insert_last(node**, int);
void printlist(node*);
// Main Function
int main()
{
node *mylist = NULL;
int i, n = 3;
for (i = 0; i < n; i++)
insert(&mylist, i);
insert_last(&mylist, 5000);
printf("My list:\n");
printlist(mylist);
free(mylist);
return 0;
}
// Add a new element to list
void insert(node **head, int value)
{
node *ptr = (node*)malloc(sizeof(node));
ptr->val = value;
ptr->next = *head;
*head = ptr;
}
void insert_last(node **head, int value)
{
if (*head == NULL)
{
insert(&head, value);
}
else
{
node *tmp = (node*)malloc(sizeof(node));
tmp->val = value;
tmp->next = NULL;
node *ptr = *head; // do przechodzenia po liscie
while (ptr->next != NULL)
{
ptr = ptr->next;
}
ptr->next = tmp;
}
}
// Print all elements from list
void printlist(node *head)
{
node *ptr = head;
while (ptr != NULL)
{
printf("%d\n", ptr->val);
ptr = ptr->next;
}
}
Po skompilowaniu
$ gcc b.c -o b && ./b
b.c: In function ‘insert_last’:
b.c:48:10: warning: passing argument 1 of ‘insert’ from incompatible pointer type
insert(&head, value);
^
b.c:34:6: note: expected ‘struct node **’ but argument is of type ‘struct node ***’
void insert(node **head, int value)
^
My list:
2
1
0
5000
Aby dodać nowy element do listy, funkcja musi pobierać "głowę". Więc skąd to ostrzeżenie? Przecież node **head to wskaźnik na wskaźnik, który wskazuje na struct. Mógłby ktoś mi to wytłumaczyć?