Hey guys,
I am currently learning C in one of my programming classes and I am having an issue with pointers to pointers.
The goal of my project is to create a tree of bredth b and depth d
I have a struct that was defined in skeleton code by my instructor (have to use this format):
Code:
struct dir { char *path; /* path to get to this dir, not including this */
char *name; /* current dir name */
int d; /* 3 <= depth level < MAXD */
int b; /* 3 <= breadth or number of sub dirs < MAXB */
struct dir *up; /* points to the parent */
struct dir **down; /* points to the sub dirs of this dir. Note the TWO *'s */
struct dir *left; /* left sibling dir, use circular link */
struct dir *right; /* right sibling dir, use circular link */
};
I can set up the tree with everything except the down node implemented and it appears to work.
In my attempt to figure it out how to get the down node to work I keep getting a segmentation fault 11.
Code:
/* create directories breadth first */void create_dir_tree(struct dir **hp,char *name,int d, int b) {
//printf("create_dir_tree init_d=%s depth=%d breadth=%d\n",name,d,b);
/* fill in here */
//test
//printf("Depth = %i\n",d);
//printf("Path = %s\n", name);
struct dir *np = malloc ( sizeof ( struct dir ));
char npnamebuf[10];
int x = 0;
sprintf(npnamebuf, "%d", x);
//printf("NPNAMEBUF = %s\n",npnamebuf);
np->path=name;
np->name=npnamebuf;
np->left=NULL;
np->up=*hp;
np->d=d;
np->b=b;
struct dir *tmp = *hp;
//struct dir *array[b];
//tmp->down=&np;
int j;
for(j=0;j<b;j++){
//array[j] = malloc ( sizeof (array[j]) );
}
if (d>0){
int i;
for(i=0;i<b;++i){
if(i<b)
{
//create temp pointer
struct dir *tp = (struct dir *) malloc ( sizeof ( struct dir ));
char tpnamebuf[10];
int y = i;
sprintf(tpnamebuf, "%d", y);
tp->path=name;
tp->name=tpnamebuf;
tp->left=np;
tp->up=*hp;
tp->d=d;
tp->b=b;
//printf("TP NAME %s\n",tp->name);
np->right=tp;
//printf("RIGHT NODE %s\n", np->right->name);
char path[100];
sprintf(path, "%s%s/", np->path, np->name);
printf("mkdir %s%s/\n", np->path, np->name);
create_dir_tree(&np,path,d-1,b);
//array[i-1]=np;
//tmp->down=&np;
np=tp;
}else if(i==b){
np->right=NULL;
//array[i-1]=np;
//tmp->down=&np;
char path[100];
sprintf(path, "%s%s/", np->path, np->name);
printf("mkdir %s%s/\n", np->path, np->name);
create_dir_tree(&np,path,d-1,b);
}
}//endfor
}else{
//printf("DONE\n");
return;
}
}
I need help implementing struct dir **down. I left my attempts in there commented out, am I at least going in the right direction or completely off target?