I'm making this ai program, but I'm having some trouble. I've made a smaller program that shows what what's wrong.
Code:
#include <stdio.h>
struct test *tree(struct test *p);
struct test {
int t;
struct test *test2;
};
int j=0;
int main()
{
struct test *root;
tree(root);
printf("Roots t %d \n",root->t);
}
struct test *tree(struct test *p)
{
struct test *malloc();
*p = *malloc(sizeof(struct test));
printf("Hi\n");
p->t=1;
if(j==0){
j++;
tree(p->test2);
printf("Test2's t %d\n", p->test2->t);
}
return(p);
}
So the main function calls tree, sending root as an argument. It is malloced space for the structure, t is set to 0, then it calls itself with a pointer in root to an instance of itself. It's t is assigned a 1, then it is supposed to be returned, print that it is eaual to 1, then return to the main function and say that its equal to 1. However, it gets a segmentation fault the first time it trys to print p->test2->t.