Brandon Ling
Brandon Ling

Reputation: 3919

Segmentation fault when passing double pointer and pointer to function

When I do:

t_node *node1;
t_node **head;
void *elem;
int c = 1;

elem = &c;
head = NULL;
node1 = malloc(sizeof(t_node));
node1->elem = elem;
head = &node1;
//add_node(node1,head); //substitute this with line above and it doesn't work
printf("%d\n",*(int*)(*head)->elem); // prints 1 and works fine

BUT WHEN I CREATE A FUNCTION CALLED ADD_NODE IT DOESN'T WORK?!??!?

void add_node(t_node *node1, t_node **head){
   head = &node1;
}

this doesn't make any sense to me... why would this cause this to not work? calling the function literally does the same exact code.

EDIT: Keep in mind the signature of the add_node is not under question. it is required of me to have that signature

Upvotes: 1

Views: 1015

Answers (3)

PQuinn
PQuinn

Reputation: 1022

In the call to the function the parameters have a scope that is only of that function, so your assignment of 'head = &node1' has no affect to variables outside the function.

To affect the variables you passed in, you must pass the address of the variables. Eg:

void add_node(t_node **node1, t_node ***head){
   *head = node1;
}

and the call would be:

add_node(&node1, &head);

Note that you must dereference the 'head' pointer in the function so the value at 'head' would be updated with the 'node1' value.

Upvotes: 3

rajneesh
rajneesh

Reputation: 1749

in 'C' varaibles are passed by reference, so to change the value in function call you should pass the pointer to variable.

correct step would be -

void add_node(t_node **node1, t_node ***head){ *head = node1; }

Upvotes: 2

Carl Norum
Carl Norum

Reputation: 224944

C is a pass by value language. Your function actually doesn't do anything at all as far as main() is concerned.

Check out this question in the comp.lang.c FAQ.

Upvotes: 3

Related Questions