Home > OS >  init() function call in C
init() function call in C

Time:10-16

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.

CodePudding user response:

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.

CodePudding user response:

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.

  • Related