0
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.

3
  • 1
    Initialize them to what? Commented Sep 4, 2010 at 21:23
  • 3
    What is strSize? Why not use std::vector and std::string? Commented Sep 4, 2010 at 21:23
  • A little '}' has been completely undermined Commented Sep 5, 2010 at 2:06

3 Answers 3

2

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 }
};
Sign up to request clarification or add additional context in comments.

2 Comments

@Johanees does this initialize the entire array or just first value of pn ?
Ah, I saw that 0x implementation somewhere but I didn't know it was 0x. Thanks for clarifying that.
1

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

Comments

0

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.

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.