5
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.

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Is there a reason you don't have to do this for {10,20}, {30,40}, and {50,60} ? That trips me up. Technically you're still assigning those values to the value at those indexes in the array
Because the above construct is available only for initialization. In pt[0] = (Point){100,200};, you are creating a temp Point and assigning it to pt[0]. You must tell compiler whether {100, 200} is a Point or int [2] or something else.
but couldn't this be similar logic in that you're also creating a temp Point {10,20} and storing that as the value of the first index in the array?
If my previous comment fails to answer your query, I would suggest you a read through C99 specs section 6.5.2.5 Compound literals.
@committedandroider You can also do something like [pt[0] = (Point){.x = 100, .y = 200};](ideone.com/Bkv5nu). Without telling the type, compiler would have no idea what x and y are.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.