开发者

Pointer to Array of Struct

开发者 https://www.devze.com 2023-01-14 16:48 出处:网络
struct bop { char fullname[ strSize ]; char title[ strSize ]; char bopname[ strSize ]; int preference; }; int main()
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.

0

精彩评论

暂无评论...
验证码 换一张
取 消