we*****@yahoo.com writes:
I have following:
struct array1
{
int id;
char *name;
};
struct array2
{
int id;
char * name;
array1 *myArray;
};
Now, I try to create an array of array2 by initialization:
array2 collection[] =
{
10, "first",
{1, "first.first"},
20, "second",
{2, "second.second"}
};
The first thing you should do is stop compiling your code with a C++
compiler; either that, or ask in comp.lang.c++.
You haven't declared a type "array1", so the declaration of the third
element of your "struct array2" is illegal. You've declared a type
called "struct array1".
The following would be legal:
struct array1
{
int id;
char *name;
};
struct array2
{
int id;
char *name;
struct array1 *myArray;
};
struct array2 collection[] = ...
[...]
How am I going to initialize something like above. Thx
C allows you to omit some braces in an initializer, but it's not
generally a good idea to take advantage of this. Enclosing the
initializers for each object and subobject in braces can make the code
easier to understand; it can also make it easier for the compiler to
catch some errors.
Assuming you want two elements in your array, you can declare it like
this:
struct array2 collection[] =
{ { 10, "first", ? },
{ 20, "second", ? } };
The question marks, of course, aren't legal; they need to be replaced
by something that initializes the myArray member of the struct array2
object.
What you want to do is initialize the myArray member (a pointer to
struct array1) so it points to an object of type struct array1. To do
this, you would need to allocate an object of type struct array1. You
can't really do this in an initializer.
Here's one possible approach:
struct array1
{
int id;
char *name;
};
struct array2
{
int id;
char *name;
struct array1 *myArray;
};
struct array1 a1_0 = { 1, "first.first" };
struct array1 a1_1 = { 2, "second.second" };
struct array2 collection[] =
{ { 10, "first", &a1_0 },
{ 20, "second", &a1_1 } };
Incidentally, "array1" and "array2" aren't very good names for
structures. I hope you're using something clearer in your real code.
--
Keith Thompson (The_Other_Keith)
ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.