segmentation fault - pointer handling
I am new with C, and I am having problems with this simple code.
I get segmentation fault when run.
Can someone please help me understand the problem here?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
|
#include <stdio.h>
#include <stdlib.h>
struct node {
int value;
struct node* left;
struct node* right;
};
struct node* new_node(int);
void insert_value_in_tree(struct node*, int);
struct node* root = NULL;
void main() {
insert_value_in_tree(root, 1);
printf("%d", root->value);
}
void insert_value_in_tree(struct node* node, int value)
{
if (!node) {
node = new_node(value);
return;
}
}
struct node* new_node(int value)
{
struct node* node = (struct node *) malloc(sizeof(struct node));
node->value = value;
node->left = node->right = NULL;
return node;
}
| |
In line 17, root is null.
You are passing a COPY of root to the function insert_value_in_tree
, so the COPY is being set.
root is a pointer, and I though that doing:
|
insert_value_in_tree(root, 1);
| |
I would be passing the address of the pointer "root" to the function. Also I declared the first parameter as pointer.
How can I fix this?
A pointer is treated like any other variable. If you pass it by value, as you are, the receiving function gets a COPY.
If you want the receiving function to be working with the original, not a copy, then pass it by reference:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
|
#include <stdio.h>
#include <stdlib.h>
struct node {
int value;
struct node* left;
struct node* right;
};
struct node* new_node(int);
void insert_value_in_tree(node*&, int);
struct node* root = NULL;
int main() {
insert_value_in_tree(root, 1);
printf("%d", root->value);
}
void insert_value_in_tree(node*& node, int value) // Pass by REFERENCE, with '&'
{
if (!node) {
node = new_node(value);
return;
}
}
struct node* new_node(int value)
{
struct node* node = (struct node *) malloc(sizeof(struct node));
node->value = value;
node->left = node->right = NULL;
return node;
}
| |
Topic archived. No new replies allowed.