Initialize a static array with struct elements

S

syang8

If I have a

struct S
{
int a;
float b;
};

how to initialize a static array of S?

static struct S sarray[] =
{
?????
};
 
E

Eric Pruneau

syang8 said:
If I have a

struct S
{
int a;
float b;
};

how to initialize a static array of S?

static struct S sarray[] =
{
?????
};

Example


struct S
{
S() : a(0){} // ctor 1
explicit S(int i) : a(i){} // ctor 2
int a;
};

int main()
{
static S s1[2] = { S(1), S(2) }; // uses ctor 2
static S s2[2]; // uses ctor 1

return 0;
}
 
R

red floyd

syang8 said:
If I have a

struct S
{
int a;
float b;
};

how to initialize a static array of S?

static struct S sarray[] =
{
?????
};

What book are you reading that doesn't explain POD struct
initialization? Note that the "struct" in the definition
of sarray[] is a C-ism, not needed in C++.

static S sarray[] =
{
{ 1, 2.3 },
{ 4, 5.6 },
{ 7, 8.9 }
};
 
S

syang8

This answers my question. Thank you.

You are right. It is a pure C quesion. I think I posted on the wrong
group.

syang8 said:
If I have a
struct S
{
  int a;
  float b;
};
how to initialize a static array of S?
static struct S sarray[] =
{
  ?????
};

What book are you reading that doesn't explain POD struct
initialization?  Note that the "struct" in the definition
of sarray[] is a C-ism, not needed in C++.

static S sarray[] =
{
    { 1, 2.3 },
    { 4, 5.6 },
    { 7, 8.9 }



};- Hide quoted text -

- Show quoted text -
 
J

James Kanze

You are right. It is a pure C quesion. I think I posted on the
wrong group.

Not really. In C++, such object types are called POD structs,
and they are very useful because they allow static
initialization, and thus avoid order of initialization problems.
Red Floyd's comment about C-ism only concerned the extra
"struct" in the data declaration.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,012
Latest member
RoxanneDzm

Latest Threads

Top