Reputation: 249
I am using a struct that, within it, it has an array of pointers to other structs of the same type. How do I assign that array at design time to have multiple elements?
Example:
struct structx {
int value;
structx *pChild[];
};
void funcY(hasChild*, int);
struct structx noChild = { 1, NULL };
struct structx otherNoChild = { 2, NULL };
struct structx childHaver = {
3,
&noChild
};
struct structx parent = {
4,
&childHaver
};
int _tmain(int argc, _TCHAR* argv[])
{
funcY(&parent, 0);
cout << endl;
funcY(&childHaver, 0);
system("pause");
return 0;
}
void funcY(hasChild* child, int childPosition)
{
if (child->pChild[0] != NULL)
{
funcY(child->pChild[childPosition], childPosition);
}
cout << child->value << endl;
}
This code is for C++ in visual studio 2008.
When I use this code, it works just fine, and prints 1, 3, 4.
However, if I try to put multiple addresses into the struct, like so:
struct structx parent = {
4,
(&childHaver, &noChild)
};
It despite sending in position 0, it will select &noChild, which should be the next position in the array.
Is there a special way to do this in the syntax that I'm missing?
Upvotes: 0
Views: 194
Reputation: 2858
Use the curly braces for initializing the array of structs.
struct structx parent = {
4,
{&childHaver, &noChild}
};
Upvotes: 1