tags:

views:

61

answers:

3
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 char array members all at once?

Edit: I know I can use string or vector but I just wanted to know out of curiosity.

+1  A: 

No, sorry. You'll need to loop through and assign values.

David Pfeffer
+2  A: 

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 }
};
Johannes Schaub - litb
@Johanees does this initialize the entire array or just first value of pn ?
brett
Ah, I saw that 0x implementation somewhere but I didn't know it was 0x. Thanks for clarifying that.
ShrimpCrackers
+1 for giving the C++0x information
Chubsdad
A: 

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.

gablin
That sounds like a good solution. I really don't intend to use code like this, I just wanted to know if you could intialize a struct member like that all at once.Thanks.
ShrimpCrackers