Initializing structures

closed account (o1vk4iN6)
I was just wondering if there is a way to initialize a structure but instead have it place a pointer in an array like so:

1
2
3
4
5
6
7
8
9
10
struct A { int a; A* b; };

A parent = { 1, NULL };

A* array[] = 
{
    {0, &parent}, //initialize structure without giving it a name and store pointer into array[0]
    parent
};


The above code doesn't work, this one does but I would rather have something like the above code which makes it more readable.

1
2
3
4
5
6
7
8
9

struct A { int a; A* b; };

A array[] = 
{
    {0, &array[1]}, // this makes it harder to understand
    {1, NULL}
};

Is the A* array[] = a typo in your first code fragment? (Should it be A rather than A* ?)
Last edited on
closed account (o1vk4iN6)
oh sorry, it's not a type, the parent should be &parent.

I want an array of pointers so that I can define stuff out of the array, since some of hte objects in the array are going to need to point to each other. I was wondering if there is a way to initialize a structure without giving it a name and placing a pointer to that into an array.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class A {
	public:
	int a; A* b;

	A(int _a, A* _b) : a(_a), b(_b) { }
};

A parent(1, NULL);

A* arr[] =
{
	&A(4, &parent), // the problem now, this is only a temporary value so the pointer ends up pointing to nothing
	&parent
};


I got a better syntax with classes, but there's still a problem.

Last edited on
Does this work?

1
2
3
4
5
6
7
8
9
10
struct A { int a; A* b; };

A parent = { 1, NULL };
A child = {0, &parent );

A* array[] = 
{
    &child,
    &parent
};
closed account (o1vk4iN6)
Yah that works, but I want to do it without having to give a name to each one. I'm going to have about 200 structures in the array but I don't want to name each one of them, it will take twice as many lines. Where as I only need 2-3 to be named, but those will be referenced by many of the structures. So it increases the error if I modify and forget to change the pointer (&array[ index ]) it will be referencing the wrong structure. As well it will be more eligible if it has a name ie you wouldn't need to go looking for the specific index.
Last edited on
Topic archived. No new replies allowed.