C Pointers

Hi guys i've built a linkedlist library in C but am having some pointer confusion, when I call the create method below it seems to have no effect on the list that I pass into it, when it should set up the root node. Included some of the code below, hope someone can help?

intList.h

1
2
3
4
5
6
7
8
9
typedef struct
{
	int data;
	struct node *next;
}node;

typedef node *linkedlist;

extern void create(linkedlist list);


intList.c

1
2
3
4
5
6
void create(linkedlist list)
{
list = malloc(sizeof(node));
list->data = 0;
list->next = 0;
}


test.c

1
2
3
4
5
int main()
{
   linkedlist list;
   create(list);
}
So you create a linkedlist object (which is a pointer to a node) and then you pass a COPY of that pointer to the function create (because this is pass-by-value), then that COPY gets altered, and then when the function ends the COPY is destroyed.

The original is untouched.
I had a feeling that was the case, how would I pass the pointer in so thats its the actual pointer?
This being C, you will have to pass a pointer to it.

1
2
3
4
5
6
7
8
9
10
11
12
void create(linkedlist* list)
{
*list = malloc(sizeof(node));
*list->data = 0;
*list->next = 0;
}

int main()
{
   linkedlist list;
   create(&list);
}
The parameter takes an argument by value. It is a local value of the function. So when the control exits the function the local variable is destroyed. The original variable list defined in main does know nothing what was done in the function. Its value will not be changed. You should declare the parameter as a pointer to linkedlist.
Last edited on
Used the code you provided Moschops but gcc gives the errors

request for member ‘data’ in something not a structure or union
request for member ‘next’ in something not a structure or union
Operator precedence, use (*list)->data = 0;
Thanks works correctly now!
Topic archived. No new replies allowed.