1

I am following an online tutorial which presents me with the following (simplified) code:

typedef struct {
    int data;
    Node* next;
} Node;


int main(){
    Node *head;
    init(&head);
    return 0;
    
}


What is the purpose & functionality of the init function? I did not define it myself, however am struggling to find documentation online as well.

3
  • 2
    Doesn't the tutorial explain that? Not much of a tutorial if it doesn't. We can't tell you for sure what it does as we didn't write that. But likely it just does *head = NULL; to initialise an empty list. Commented Oct 16, 2021 at 10:25
  • init isn't in the standard library Commented Oct 16, 2021 at 10:26
  • looks like the tutorial has its own init function that initialises the head Commented Oct 16, 2021 at 10:26

2 Answers 2

4

For starters this declaration

typedef struct {
    int data;
    Node* next;
} Node;

is incorrect. The name Node used in this data member declaration

    Node* next;

is undefined.

You need to write

typedef struct Node {
    int data;
    struct Node* next;
} Node;

As for your question then in this declaration

Node *head;

the pointer head has an indeterminate value because it is not initialized.

So it seems the function init just initializes the pointer. You need to pass the pointer by reference through a pointer to it. Otherwise the function will deal with a copy of the pointer head. Dereferencing the pointer to pointer you will get a direct access to the original pointer head that can be changed within the function. That is the function can look the following way

void init( Node **head )
{
    *head = NULL;
}

Pay attention to that you could just write in main

Node *head = NULL;

without a need to call the function init.

Sign up to request clarification or add additional context in comments.

Comments

2

I think that the init function is gonna be implemented in the next videos. I suppose that your teacher wants to use an init function to set some values if you create a new Node (or a struct in this case) to prevent some easter eggs undefined behaviour.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.