Reputation: 358
The error encountered is: expected expression before '{' token. Why it is so?
#include <stdio.h>
int main ()
{
struct test
{
char a[100];
int g;
} b[2];
b[0] = {"Maharshi", 5};
b[1] = {"Hello", 6};
printf("%u %u", &b[0], &b[1]);
return 0;
}
Upvotes: 1
Views: 45
Reputation: 98
You cannot use list initialization when the struct is already declared ! You could have used it like this :
int main () {
struct test{
char a[100];
int g;
}b[2] =
{{"Maharshi", 5},
{"Hello", 6}};
printf("%u %u", b[0].g, b[1].g);
return 0;
}
(Note that the inside braces are optionnal.)
Upvotes: 2
Reputation: 311108
You may not assign initializer lists to already defined objects.
b[0] = {"Maharshi", 5};
b[1] = {"Hello", 6};
But you could do what you want by means of compound literals:
b[0] = ( struct test ){ "Maharshi", 5 };
b[1] = ( struct test ){ "Hello", 6 };
Or use the initializer lists when the array is being defined.
Upvotes: 5