I am looking to create a binary tree and then print it out. I am getting some strange errors I cant fix.
#include <stdio.h>
#include <string.h>
struct animalTree
{
char data[100];
struct animalTree *left;
struct animalTree *right;
};
typedef struct animalTree aTree;
void fillTree(FILE*, struct animalTree*);
int readNext(char*, FILE*, int*);
void printTree(struct animalTree*);
struct aTree *makeNode(char*);
aTree* root;
int main()
{
FILE *fp;
fp=fopen("animals", "r");
char stuff[40];
if(fp != NULL)
{
fillTree(fp, root);
printTree(root);
}
else
{
root = (aTree*)makeNode("Horse");
}
fclose(fp);
return 0;
}
void fillTree(FILE* fp, struct animalTree *node)
{
char data[100] = {""};
int isNULL = 1;
if(readNext(data, fp, &isNULL))
return;
if(isNULL == 1)
{
node = (aTree*)makeNode(data);
fillTree(fp, node->left);
fillTree(fp, node->right);
}
}
void printTree(struct animalTree *root)
{
if(root == NULL)
{
printf("%s", "here");
return;
}
printf("%s", root->data);
printTree(root->left);
printTree(root->right);
}
int readNext(char* data, FILE* fp, int* isNULL)
{
fgets(data, 100, fp);
if(feof(fp))
return 1;
else
{
if(strcmp(data, "NULL"))
{
isNULL = 1;
}
else
{
isNULL = 0;
}
return 0;
}
}
struct aTree* makeNode(char* data)
{
aTree *node;
node = (aTree*)malloc(sizeof(aTree));
if (node)
{
strcpy(node->data, data);
node->left = NULL;
node->right = NULL;
}
return node;
}
ERRORS:
user@ubuntu:~/Desktop/Assignment2/C$ gcc program.c
program.c: In function ‘readNext’:
program.c:74:11: warning: assignment makes pointer from integer without a cast [enabled by default]
program.c: In function ‘makeNode’:
program.c:87:17: warning: incompatible implicit declaration of built-in function ‘malloc’ [enabled by default]
program.c:94:2: warning: return from incompatible pointer type [enabled by default]
I am aware these are warnings and that the program can run which i have done but it seems like the root that it passes to print is sitting at the end on a NULL node and never goes into the print. Other times with minor changes I have got seg faults.
For starters is my root variable doing what it's suppose to. It holds the start of the tree right?
I feel like root is being changed and I can't print from it but then again I'm not really sure what's happening.
The animals file is:
Does it purr?
cat
NULL
NULL
Does it bark?
dog
NULL
NULL
Does it walk?
horse
NULL
NULL
fish
NULL
NULL
Anyway thanks for the help