Pointer to Array of Struct
struct bop
{
char fullname[ strSize ];
char title[ strSize ];
char bopname[ strSize ];
int preference;
};
int main()
{
bop *pn = new bop[ 3 ];
Is there a way to initialize the 开发者_Python百科char array members all at once?
Edit: I know I can use string or vector but I just wanted to know out of curiosity.
Yes. You can initialize them to all-0 by value-initializing the array
bop *pn = new bop[ 3 ]();
But in fact I would prefer to use std::string
and std::vector
like some commenter said, unless you need that struct to really be byte-compatible with some interface that doesn't understand highlevel structures. If you do need this simplistic design, then you can still initialize on the stack and copy over. For example to "initialize" the first element
bop b = { "bob babs", "mr.", "bobby", 69 };
memcpy(pn, &b, sizeof b);
Note that in C++0x you can say
bop *pn = new bop[3] {
{ "bob babs", "mr.", "bobby", 0xd00d },
{ ..., 0xbabe },
{ ..., 69 }
};
No, sorry. You'll need to loop through and assign values.
If I'm not mistaken, you could add a constructor to the struct which initializes the values to default values. This is similar if not identical to what you use in classes.
精彩评论