Originally Posted by
whiteflags
Can you please paste a small, complete program that we can compile, which still exemplifies the problem? I'm becoming concerned because you have several snippets of code on different forums. I don't want to fix one version of the source code only for you to think you are working on the same version, but you actually have something different in the editor. We need to fix something that has a main() so that we're both working on common ground.
Short, Self Contained, Correct Example
Another reason I am asking is because it is helpful to see how you are using the code you have shown so far. There may be other problems which you are not aware of.
The only reason I don't share full code is that I don't want to make post more complicated than intended. So I only share the part of code which causes problem. But since you asked here a code you can compile:
Code:
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
struct NodeData {
char name[99];
};
struct BstNode {
NodeData *data;
BstNode *left;
BstNode *right;
};
BstNode *NewBstNode(NodeData*);
BstNode *insertData(BstNode*, NodeData*);
void serialize(BstNode*, FILE*);
void deSerialize(BstNode*&, FILE*);
bool searchData(BstNode*, NodeData*);
int main() {
BstNode *root = NULL;
NodeData *data = NULL;
cin>>data->name;
insertData(root, data);
cin>>data->name;
insertData(root, data);
FILE *fp = fopen("db.bin", "w");
serialize(root, fp);
return 0;
}
BstNode *NewBstNode(NodeData *data) {
BstNode *newNode = new BstNode();
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
BstNode *insertData(BstNode *root, NodeData *data) {
if(root == NULL) {
root = NewBstNode(data);
} else {
if(memcpy(data->name, root->data->name, 1) <= 0) {
root->left = insertData(root->left, data);
} else {
root->right = insertData(root->right, data);
}
}
return root;
}
void serialize(BstNode *root, FILE *fp) {
fwrite(root, sizeof(struct BstNode), 1, fp);
serialize(root->left, fp);
serialize(root->right, fp);
}
void deSerialize(BstNode *&root, FILE *fp) {
NodeData *data = NULL;
if(!fread(data, sizeof(struct BstNode), 1, fp))
return;
root = NewBstNode(data);
deSerialize(root->left, fp);
deSerialize(root->right, fp);
}
bool searchData(BstNode*, NodeData*) {
return false;
}
I didn't start writing search function yet. Inside main when you get to the line "insertData(root, data);" it goes to that function and at 6th line in that function program stops. So I thought there is something I did wrong with pointers and references at that line hence shared only that function.