I am trying to implement a linked list in C:
struct Node{
struct Node *next;
void *data;
};
With an insert function:
void insert(void *p2Node, void *data)
{
struct Node *newNode;
struct Node **p2p2Node= (struct Node **)p2Node;
if (newNode = malloc(sizeof(struct Node))) /* if successfully allocated */
{
newNode->data = data;
if ((*p2p2Node) != NULL) /* if the list is not empty */
{
newNode->next = (*p2p2Node)->next;
(*p2p2Node)->next = newNode;
}
else
(*p2p2Node) = newNode;
p2Node = p2p2Node;
}
printf("Inside the insert: %s\n", (*p2p2Node)->data);
}
I called insert in main():
int main()
{
char *setA = "liquid ";
char *setB = " lgd";
char *setC = "sample";
struct Node *nList = malloc(sizeof(struct Node));
insert(nList, setC);
printf("2Get %s\n", nList->data);
return 0;
}
No error or warning was reported, but the value was only changed inside the insert. Back to main() the linked list is still empty.
I do not understand: nList in main() is a void pointer. Inside insert(), *p2Node is not altered, I used p2p2Node to change the value p2Node points to, why is it not working? Did I mismatch the pointers? Is there a way I can make it work without modifying the parameter of insert()?
Thank you.
struct Node **p2p2Node= (struct Node **)p2Node;If you want the pointer value to be modified by the function, then the parameter to the function must be a pointer-to-pointer.nList, to be a pointer of a pointer to a struct? I mean, a pointer to a pointer is still a pointer, it should be okay to be passed intoinsertasvoid *p2Node?void insert(struct Node **p2p2Node, void *data)and when you call it for an empty list,nListshould be NULL. Then you callinsert(&nList, setC);You should also usecallocwhen allocating inside theinsertfunction, OR explicitly setnextto NULL. Currently, the value of the next-pointer on the first node inserted is undefined.