I am a beginner in C. I am working on an assignment to create a tree data structure. I have an if in main where I check if top is NULL before doing some action. Within my function to create the top pointer, it returns NULL right after being created (as expected, I haven't pointed it at anything yet). However when execution goes back to main, it returns an address even though I haven't assigned it one. So, my if doesn't work like I want it to.
I have noticed, if I set top to NULL from within main, then it sticks.
My question is, why does the address of top change from NULL to something else when execution returns to main? Have I done something in my code to unknowingly give point top to an unintended address?
//struct for org chart tree
typedef struct org_tree{
struct employee *top;
} org_tree;
//create org tree
void CreateTree(org_tree *t)
{
org_tree *temp;
temp = malloc(sizeof(org_tree));
t = temp;
printf("%p\n", t->top); **here returns (nil) as expected
}
//main program
int main(void)
{
FILE *file;
file = fopen("employee.list", "r");
printf("file opened\n");
org_tree t;
CreateTree(&t);
printf("%p\n", t.top) **here returns a memory location
t.top = NULL **if I add this, then if below works.
char mgr[20], st1[20], st2[20], st3[20], st4[20];
while(fscanf(file, "%s %s %s %s %s\n", mgr, st1, st2, st3, st4)!=EOF)
{
employee *m;
if (t.top !=NULL) **this if not working like I want it to because NULL doesn't "stick" unless set in main.
{
///remaining code not relevant to question//
}
}
...