I'm trying to simulate a tree with d number of depths and n number of nodes. I call the function create_tree and pass arguments of the root folder, the maximum depth and nodes. So if I call root 2 3, I expected as follows
root/0
root/1
root/2
root/0/0
root/0/1
...
root/2/2
However, my code repeats
root/0
root/1
root/2
root/0
root/1
root/2
I'm suspecting that my array of struct d's isn't working as expected. Can anyone help me understand the cause of this?
Thank you.
Code is posted below
Code:
struct d {
char *path; //path to node
char *name; //path + current node = name
struct dir *up; //to parent
};
void create_tree(struct d **p,char *name,int depth, int children) {
struct dir *cur_head, *tp;
cur_head=malloc(sizeof(struct dir));
tp=malloc(sizeof(struct dir));
cur_head->up=*p;
cur_head->name=(char *)name;
cur_head->path=(char *)name;
tp=cur_head;
struct dir open[1];
open[0]=*tp; //set up for first root dir
int open_size = sizeof(open)/sizeof(struct dir);
int i;
for(i=0; i<depth; i++){
double breadth_as_double = pow(children,i+1); //size of array c^d
int breadth_size = (int)breadth_as_double;
struct dir array_dir[breadth_size];
int pos_in_array = 0;
int pos_in_open;
for(pos_in_open=0; pos_in_open<open_size; pos_in_open++){
struct dir *cur_parent;
cur_parent=malloc(sizeof(struct dir));
cur_parent=&open[pos_in_open];
printf("current_parent: %s\n", cur_parent->name);
int j;
for(j=0; j<children; j++){
struct dir *breadth_p;
breadth_p=malloc(sizeof(struct dir));
char buffer[8];
char name_buff[1024];
snprintf(buffer,sizeof(buffer), "/%d", j);
breadth_p->up=cur_parent;
breadth_p->path=breadth_p->up->name;
snprintf(name_buff,sizeof(name_buff), "%s%s",breadth_p->path,buffer);
printf("name of dir: %s\n", name_buff); //remove later
breadth_p->name=name_buff;
array_dir[pos_in_array]=*breadth_p;
pos_in_array++;
}
}
open_size = breadth_size;
struct dir open[breadth_size]; //does this initalize a new array?
int x;
for(x=0;x<breadth_size;x++){
struct dir *temp;
temp=malloc(sizeof(struct dir));
temp=&array_dir[x];
open[x]=*temp;
printf("loop test: %s\n", temp->name);
}
}
}