Reputation: 165
So i've been teaching myself linked lists and been messing around trying to write some very basic functions for them. Basically what i've been working with
struct ListNode{
int data;
ListNode *next
};
I'm trying to make a function to add numbers to a list and what i've gotten so far is
void addToList(int numberToAdd, struct ListNode *headOfList){
ListNode *newItem=new ListNode;
newItem->data=numberToAdd;
if(headOfList==NULL){
newItem->next=NULL;
headOfList=newItem;
}}
So far i've only tried to add a single ListNode to an empty list declared as
ListNode *head=NULL;
in my main function. the problem that i'm having is that after I do my
addToList(someRandomNumber,head);
I get an error if I do this,
cout<<head->data;
but if I go into my addToList function and do
cout<<headOfList->data;
it works perfectly fine. Why is this so?
Upvotes: 0
Views: 155
Reputation: 158619
headOfLst
is being passed by value so when you modify the variable it is not being reflected in main
:
void addToList(int numberToAdd, struct ListNode *headOfList){
^^^^^^^^^^^^
If you pass it has a double pointer you will be able to modify the pointer itself:
void addToList(int numberToAdd, struct ListNode **headOfList){
then the assignment later on would be:
*headOfList=newItem;
Edit
and the call in main
should be modified like so:
addtolist(1,&head);
Another option, is to pass a reference to a pointer:
void addToList(int numberToAdd, struct ListNode *& headOfList){
^
no other code has to be modified in that case.
Upvotes: 1
Reputation: 7845
When you pass your headList
argument to addToList
you are actually passing a copy of it. headOfList
and head
are independent pointers. This means that when you modify your head pointer inside the function to point to anything else and return, the head
pointer is still unmodified (pointing to NULL). When you execute cout<<head->data;
, you are dereferencing a NULL pointer. (head->data
is equal to (*head).data
.)
The solution in this case is to add another level of indirection, that is, pass a pointer to a pointer to a ListNode
, as Shafik explains:
addToList(someRandomNumber, &head);
Upvotes: 0