Hi Salem,
Thank you for your reply.. As you mentioned before, I stored the return of insert() to the struct (T). Also, changed the main() to int main() that returns 0 at the last part.. I also checked and revised my code logic against your seg-fault error checklist, however, I still get the seg-fault error.. Would you explain a little bit more detail what si the error is in this small program? I attached my revised code here..
Code:
#include <stdio.h>
#include <stdlib.h>
typedef struct BSTree *BST;
struct BSTree {
int elm;
BST left;
BST right;
};
BST makeEmpty(BST T) {
if(T != NULL) {
makeEmpty(T->left);
makeEmpty(T->right);
free(T);
}
}
BST insert(int a, BST T) {
if(T == NULL) {
T = malloc(sizeof(struct BSTree));
if(T == NULL) {
fprintf(stderr, "insert: FATAL - malloc failed!\n");
} else {
T->elm = a;
T->left = T->right = NULL;
}
} else {
if(a < T->elm) {
T->left = insert(a, T->left);
} else {
if(a > T->elm) {
T->right = insert(a, T->right);
}
}
}
return T;
}
int main() {
BST T;
int element, i;
FILE *fp;
T = makeEmpty(T);
if((fp = fopen("data_search.txt", "r")) == NULL) {
printf("main: FATAL - Failed to open data_search.txt!\n");
return 0;
} else {
printf("main: Success to open data_search.txt\n");
while(!feof(fp)) {
element = getc(fp);
T = insert(element, T);
}
}
return 0;
}
Thank you so much..