here is the code
struct point_tag {
int x;
int y;
};
typedef struct point_tag Point;
int main(void)
{
Point pt[] = { {10,20}, {30, 40}, {50,60}};
pt[0] = {100,200};
}
When i do pt[0] = {100, 200}
, the compiler keeps complaining of
error:expected expression before '{' token
I don't really get that though. Isn't the expression before the { token assignment operator(=)?
I don't understand why the assignment would be an issue though. the value at address pt refers to an array of Point. I am just setting the 0th Point to be this new point and i know that assigning a struct in a format like {100,200}
is legal where the elements inside that array are just fields.
For assignment, typecast the value to type Point to make it a compound literal:
pt[0] = (Point){100,200};
Live code using gcc
This is equivalent to
{
Point temp = {100,200};
pt[0] = temp;
}
p.s. Compound literal is not available in old strict C89 compliant compiler. It is avilable in GCC for C89 as extension and in C99 compound literal is a core feature.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With