retagged
682 views
1 votes
1 votes

What is the difference when I write in program
 

mynode * head;
add_node(&head,10);

add_node( struct node ** head, into value);



To this
 

mynode *head;
add_node (head,10);

add_node( struct node* head, into value)



Which is the correct way of writing?

retagged

3 Answers

Best answer
3 votes
3 votes

Both can be used, Although first is considered better due to certain flexibility available inside the function to change where head will point. 

In first case , you are sending a double pointer(address of head pointer)  to  function as argument,  so you can change value of head pointer(where head is pointing)   using

void test_Func(struct Node **head) //Func Definition 
{
    *head=sm addr;
}
test_Func(&head);           //Func Call

In second case, directly changing head inside function is not possible as it's the value of head pointer itself that you are passing  so you cannot access its address to change it(head is just a local var containing address pointed by head and not address of head itself) . To change it you can return  new head value (an address essentially)  at end and at the place of fun call reassign to head pointer. 

struct Node * test_Func(struct Node *head) //Func Definition 
{
    head=sm addr;
    return head;
}
head= test_Func(head);           //Func Call
edited by
1 votes
1 votes

add_node( struct node ** head, into value)

is correct way.double pointer will help you to directly modify conents of head pointer in main function.

FOR SIMPLICITY ASSUME *head as some variable of type int.

so now you are passing address of this variable to the function,

 add_node( struct node* head, into value) is wrong.to make this correct you should reuturn new address that your function modified and assign this address as a new head.

 head =  add_node( struct node* head, into value)

0 votes
0 votes
Both can be used but it is based on how you define structure elements.

Related questions

1 votes
1 votes
2 answers
2