-2

why initialization in structure is done where object is created please see below code?

struct st {
    int i;
    char ch;
    float f;
};
int main() {
    struct st var = {2, 'h', 33.45}, var2; // here initialization is gud

    var2= {3, 't', 55}; // here initialization is bad why?

    printf("%d %c %f\n", var.i, var.ch, var.f);
    printf("%d %c %f\n", var2.i, var2.ch, var2.f);
}
rost rost
  • 1
  • 2
  • 2
    `var2.i={3,'t',55};` how possible what it indicate from your point of view? look you accessing `int i` now not whole `struct`. it should be `var2`. what exactly you want? need to learn more about `c` for initialization and assignment. – Jayesh Bhoi Aug 25 '14 at 04:53
  • I assume you mean `var2`, not `var2.i`, then it's a duplicate. – Yu Hao Aug 25 '14 at 04:57
  • but you can write this `var2 = (struct st){3, 't', 55};` c99 later. – BLUEPIXY Aug 25 '14 at 09:05

2 Answers2

1

After declaration, the below syntax can should be followed to init the structure elements.

    var2.i=2;
    var2.ch='t';
    var2.f=55;

This is the syntax of C language.

mahendiran.b
  • 1,315
  • 7
  • 13
0

It should be

struct st var2 = {3,'t',55};

or

struct st var2;
var2.i = 3;
var2.ch = 't';
var2.f = 55;
cppcoder
  • 22,227
  • 6
  • 56
  • 81