• Advertisement
Sign in to follow this  

structure initialization error

This topic is 4811 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I give these codes:
#include<stdio.h>
struct a
{
 int b;
 char c;
};
struct d
{
 int id;
 struct a xx[2];
};
void main(void)
{

struct d*  structptr;
struct d example;
structptr=&example;
structptr->id=1;
structptr->xx[0]={2,'x'};/*error here*/
structptr->xx[1]={3,'y'};/*error here*/

/*if I use these codes ,it will have no error:
structptr->xx[0].b=2;
structptr->xx[0].c='x';
*/

printf("%d,%d,%c",structptr->id,structptr->xx[0].b,structptr->xx[0].c);
}
My compiler is Turbo C,why did it happen?

Share this post


Link to post
Share on other sites
Advertisement
Neither C nor C++ allow initialization of structures. Even if they did, you can perform initialization when a variable is declared. So this works:

int var[5] = {1,2,3,4,5};

But this doesn't:

int var[5];
var = {1,2,3,4,5};

With structs you're better off to create constructors if you want to perform initialization.

Share this post


Link to post
Share on other sites
thx,mabe I used an ill-suited word 'initialization'
I just want to know if I can only use these:
structptr->xx[0].b=2;
structptr->xx[0].c='x';

but not these:
structptr->xx[0]={2,'x'};

Share this post


Link to post
Share on other sites
struct initialisers only work at the point of declaration.

struct foo {
int x;
int y;
};

void bar() {
foo f = { 1, 2 }; // good
foo g;
g = { 3, 4 }; // bad
}

Share this post


Link to post
Share on other sites
And thus:

struct d example = { 1, // id
{ {2, 'x'}, // x[0]
{3, 'y'}, // x[1]
} // x
};
// should work, as far as I know

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement