Tom Davis
Tom Davis

Reputation: 23

Dynamically Allocated Array of Pointers in Struct

I want to do something like this.

typedef struct Test{
  int value;
  struct Test* parent;
  struct Test** children;
}Test;

So I want a node that points to another parent structure. Then I want a dynamically allocated array that points to child nodes. My question is that I have no idea how this would work syntactically.

For example,

Test* first;
Test* second;
Test* third;
(*third).value = 1;
(*first).parent = second;
(*first).child[0] = third;
printf("%d\n",(*first).(*child[0]).value);

doesn't compile. I'm assuming I need to do something with malloc to allocate space for the array of pointers but I'm not sure. Also I'm not sure how I would access the "value" of the parent and child directories.

Upvotes: 2

Views: 1141

Answers (1)

std''OrgnlDave
std''OrgnlDave

Reputation: 3968

EDIT: I've added an ideone link to the end that implements all the concepts for you.

Sorry for the terseness of this answer, I am hoping it will show you how to do it properly.

Test* first = (Test *)malloc(sizeof(Test));  // malloc(sizeof(Test)) allocates enough memory to hold a Test struct
Test* second = (Test *)malloc(sizeof(Test));
first->value = 1; // -> is the proper way to dereference pointers in this situation (sorry wrong term? I am up late) but I suppose your style can work, it just gets a bit confusing IMO
first->*child = (Test *)malloc(intptr_t * number_of_children); // intptr_t will make sure you have the right size of a pointer, you could also use sizeof(Test *) instead. i.e. malloc(sizeof(Test *));
first->child[0] = second; // The array-style subscript is just more readable IMO
printf("%d\n",first->child[0]->value); // child[0]-> will handle the dereferencing in a nice way

But I'm going to show you a bit of a trick to make your life easier

typedef Test* test_array;

// ...later, in the struct...
test_array* child;

// ...later, in the malloc place...

first->child = (test_array *)malloc(sizeof(test_array *) * number_of_children);

Everything else stays the same, you just get much easier to understand syntax IMO. Helps deal with those tricky double stars.

EDIT: here's the link - http://ideone.com/TvSSB

Upvotes: 1

Related Questions