retagged
1,460 views
1 1 vote

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?

3 Answers

Best answer
3 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 1 vote

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 0 votes
Both can be used but it is based on how you define structure elements.
Position:
Show:

Related questions

0 0 votes
3 3 answers
2.1k
2.1k views
Nitesh Choudhary asked Jun 6, 2017
2,109 views
#include <stdio.h void swap(int *p, int *q) { int *t; *t=*p; *p=*q; *q=*t; printf("a=%d b=%d\n",*p,*q); } int main(void) { int a=5; int b=10; swap(&a,&b); printf("a=...
7 7 votes
2 2 answers
313
313 views
GO Classes asked Jun 29
313 views
What is the output of the following code?#include <stdio.h struct Item { int code; int price; }; void update(struct Item *p) { p->price = p->price + 20; (*p).code = (*p)....
6 6 votes
2 2 answers
284
284 views
GO Classes asked Jun 29
284 views
What is the output of the following code?#include <stdio.h struct Box { int width; int height; }; int main() { struct Box b = {4, 6}; struct Box *p = &b; p->width = p->wi...
4 4 votes
2 2 answers
289
289 views
GO Classes asked Jun 27
289 views
What will happen in the following code?#include <stdio.h #include <stdlib.h int main() { int *p = (int *)malloc(sizeof(int)); *p = 10; free(p); printf("%d", *p); return 0...