0

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?

4
  • 1
    Is it a requirement that you use an array of pointers to structx? Can you use std::vector<struct*> instead? Commented Jun 5, 2014 at 16:55
  • (&childHaver, &noChild) is using the comma operator, not passing multiple things. And that struct hack isn't valid C++. Commented Jun 5, 2014 at 16:58
  • Vectors might work, but it depends on my Head of Development. He doesn't like them. What's the syntax for passing multiple things? Commented Jun 5, 2014 at 17:03
  • you don't have any arrays of structs. Commented Jun 5, 2014 at 17:06

1 Answer 1

1

Use the curly braces for initializing the array of structs.

struct structx parent = {
4,
{&childHaver, &noChild}
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.