Skip to main content
gamedev.net
🔒 Locked

structure initialization error

Started by econoy Dec 17, 2004 at 10:01 AM 4 replies 600+ views
Original Post
econoy
econoy
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?
Morbo
Morbo
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.
econoy
econoy
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'};
Miserable
Miserable
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}
Zahlman
Zahlman
And thus:
struct d example = { 1, // id                     { {2, 'x'}, // x[0]                       {3, 'y'}, // x[1]                     } // x                   };// should work, as far as I know
econoy
econoy
Thanks!^-^
I think I get it.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.