Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't this array of structure assignment compile?

Tags:

arrays

c

struct

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.

like image 540
committedandroider Avatar asked Oct 30 '14 06:10

committedandroider


1 Answers

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.

like image 159
Gyapti Jain Avatar answered Nov 14 '22 23:11

Gyapti Jain