I’ve been trying to make a tree with directories with pointers in C.
I thought it would be easier to use some kind of struct with pointers, which would resemble a class in Java.
so I would using something like this:
struct d
{
struct d *up /*point to parent*/
struct d *down /*point to child*/
struct d *right /*point to right*/
}
generate_tree(struct **d)
{
/*my code*/
}
I’m trying to make multiple struct d’s and connect them. So what I’m assuming that I have to do is create and allocate a pointer for the directory then initialize a struct d and have the created pointer to point inside the struct d. My question is how would I create the d and set the *up, *down, and *right?
Thanks for helping
You dynamically allocate a
struct dwithmalloc(). Ie,Once you have a pointer to an newly-created
struct d, you assign to it’s fields just like any other C structure:The trick, of course, is what you assign to those fields. Well, from their types,
struct d *, it has to be a pointer to astruct d. So, either you assign the NULL pointer constant, which indicates there’s nothing there, or you assign the address of some otherstructd dobjects. For example,I don’tknow if this struct is intended to be more than a toy example, but it looks like a node in some sort of tree structure. If that’s the case, you’d want to write various helper functions that hide most of this pointer manipulation.
and so on for the relevant operations on whatever it is you’re building.