The problem is my root stays NULL when I need it to change after the first call of my addContact function.
I have tried pointer to pointer but got an access error... This 0x28... Is all I remember about the error. I have also tried using *& in the parameter of my addContact function but to no avail. What I will show in code is what I thought would fix it but my logic is flawed obviously. Any help would be much appreciated!
This is in my header file.
struct Transaction {
std::string ID;
std::string lName;
std::string fName;
std::string pNum;
std::string eMail;
std::string address[7];
};
struct Node {
Transaction data;
Node* left;
Node* right;
};
Node* addHelper(Transaction data) {
Node* newNode = new Node();
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}
Node* addContact(Node* root, Transaction data) {
if (root == NULL) {
std::cout << "Checking to see if root stays NULL" << std::endl;
root = addHelper(data);
}
else if (data.lName <= root->data.lName) {
root->left = addContact(root->left, data);
}
else {
root->right = addContact(root->right, data);
}
return root;
}
This is in my Main file.
#include <iostream>
#include <fstream>
#include "Header.h"
using namespace std;
int main() {
ifstream file; file.open("bt.txt");
Transaction inputArray[3];
for (int i = 0; i < 3; i ) {
file >> inputArray[i].ID >> inputArray[i].lName >> inputArray[i].fName >> inputArray[i].pNum >> inputArray[i].eMail;
for (int j = 0; j < 7; j ) {
file >> inputArray[i].address[j];
}
}
Node* root = NULL;
root = addContact(root, inputArray[0]);
root = addContact(root, inputArray[1]);
root = addContact(root, inputArray[2]);
}
CodePudding user response:
In addContact
you have modified the root
parameter, but that is local to the function and has no bearing on the value passed in.
Sticking with raw pointers, you may want to pass in a pointer to a pointer, so you can modify the pointer you're pointing to.
Node* addContact(Node** root, Transaction data) {
if (*root == NULL) {
std::cout << "Checking to see if root stays NULL" << std::endl;
*root = addHelper(data);
}
else if (data.lName <= (*root)->data.lName) {
(*root)->left = addContact(&(*root)->left, data);
}
else {
(*root)->right = addContact(&(*root)->right, data);
}
return *root;
}
As noted in comments, you can make addHelper
a constructor for Node
.
struct Node {
Transaction data;
Node* left;
Node* right;
Node(Transaction data) : data(data), left(nullptr), right(nullptr) { }
};