1

I'm new with C.

I writing simple linked list application.

this is my code :

typedef struct
{
    struct node * NextNode;
    int data;
}node;

void addNode(int data, node * Head)
{
    if (Head == NULL)
    {
        Head = malloc(sizeof(node));
        Head->data = data;
        Head->NextNode = NULL;
        return;
    }
    node* CurrentNode = Head;
    node* _Newnode = malloc(sizeof(node));
    (*_Newnode).data = data;
    _Newnode->NextNode = NULL;
    while (CurrentNode->NextNode != NULL)
    {
        CurrentNode = CurrentNode->NextNode;
    }
    CurrentNode->NextNode = _Newnode; 
}

The problem rise is when passing Head = NULL after passing head= NULL ,the Head didn't change and remained NULL

What am I doing wrong ? can you please also explain what is happening underneath ?
thanks

Mgetz
  • 5,108
  • 2
  • 33
  • 51
LordTitiKaka
  • 2,087
  • 2
  • 31
  • 51

2 Answers2

2

The pointer is passed by value - if you update it, all you are doing is updating a local copy of it. If you want to update the pointer, you should pass a pointer to it, and update its dereference:

void addNode(int data, node ** Head)
{
    if (*Head == NULL)
    {
        *Head = malloc(sizeof(node));
        *Head->data = data;
        *Head->NextNode = NULL;
        return;
    }
    node* CurrentNode = *Head;
    node* _Newnode = malloc(sizeof(node));
    (*_Newnode).data = data;
    _Newnode->NextNode = NULL;
    while (CurrentNode->NextNode != NULL)
    {
        CurrentNode = CurrentNode->NextNode;
    }
    CurrentNode->NextNode = _Newnode; 
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
1

The pointer node * Head is passed by value, if you want to assign to Head you need to pass it as node**Head e.g. a pointer to the pointer.

void addNode(int data, node ** Head)
{
    if (*Head == NULL)
    {
        *Head = malloc(sizeof(node));
        *Head->data = data;
        *Head->NextNode = NULL;
        return;
    }
    node* CurrentNode = *Head;
    node* _Newnode = malloc(sizeof(node));
    (*_Newnode).data = data;
    _Newnode->NextNode = NULL;
    while (CurrentNode->NextNode != NULL)
    {
        CurrentNode = CurrentNode->NextNode;
    }
    CurrentNode->NextNode = _Newnode; 
}
Mgetz
  • 5,108
  • 2
  • 33
  • 51
  • can you explain what is happening here ? what exactly is passed ? – LordTitiKaka Oct 14 '14 at 19:26
  • 1
    @LordTitiKaka when you pass a pointer you're actually passing a value that holds the address of a location in memory. To return a pointer as an out value you need to pass the address of the location of the original pointer in memory. So if I have a pointer `node *Head` that I want this function to give a value to I pass it as `&Head` to the function, by doing so I pass the location of the pointer and not the pointer itself. – Mgetz Oct 14 '14 at 19:29