Double Pointer BST

I'm working on making a double pointer implementation of a BST, but I'm getting a segfault.

main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
#include <stdlib.h>
#include <iostream>
#include "bst.h"

using namespace std;

int main() {
	BSTNode** root = NULL;
	addNode(root, 5);
	
	return 0;
}


bst.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <stdlib.h>
#include <iostream>

using namespace std;

typedef struct S_BSTNode {
	int number;
	S_BSTNode* left;
	S_BSTNode* right;
} BSTNode;

bool addNode(BSTNode** root, int number) {
	if ( *root == NULL ) {
		BSTNode *newNode = new BSTNode;
		newNode->number = number;
		*root = newNode;
		return true;
	}
        //... Rest hidden
	return false;
}


The problem is that I am trying to check if *root == NULL when **root is NULL. How can I initialize root in my main so *root == NULL is a valid call?
closed account (o3hC5Di1)
Hi there,

I'm not sure about this - no expert here - but something seems off to me in this logic.

You assign a value to BSTNode** root, even though it is null.
To me that would imply that [code*root[/code] holds an address to that nullpointer.
If [code]*root[/code] were NULL - it wouldn't point to the **root - it would point nowhere.
Hence you get a segfault when trying to read from it.

Hopefully that can help you understand the problem, let us know if you need more specific directions to a solution and I'm sure one of the experts around here will be happy to help.

All the best,
NwN
This:
1
2
3
4
5
6
7
8
9
10
11
12
#include <stdlib.h>
#include <iostream>
#include "bst.h"

using namespace std;

int main() {
	BSTNode* root = NULL; // Note: this is the pointer to the root
	addNode(&root, 5); // Now provide the pointer to the pointer to root (so that you can modify the pointer to root)
	
	return 0;
}
Topic archived. No new replies allowed.