Is there an efficient way to assign/convert a struct to array and vice-versa?
The struct I have is as follows:
struct A {
int x, y;
}
struct B {
struct A start;
struct A end;
}
Basically they contain xy coordinates for start and end positions.
I need to assign them efficiently however currently I can only do this
/* sample code */
struct B b;
b.start.x = arr[i];
b.start.y = arr[i];
b.end.x = arr[i];
b.end.y = arr[i];
/* I can't do this in ANSI C / C89 as compound literals only allow constants */
b = (struct B) {(struct A) {arr[0], arr[1]}, (struct A) {arr[2], arr[3]}};
I can use compound literals as well but it gives me a warning in gcc when I compile with flags -Wall -pedantic -ansi
Is there a way to reduce those 4 lines of assignment to just one without getting a warning with the flags mentioned above.
Regards
Edit: fixed compound literal syntax
struct A
{
int x, y;
};
struct B
{
struct A start;
struct A end;
};
void InitA(struct A* s, int x, int y)
{
s->x = x;
s->y = y;
}
void InitB(struct B* s, int x1, int y1, int x2, int y2)
{
InitA(&s->start, x1, y1);
InitA(&s->end, x2, y2);
}
void InitBFromArray(struct B* s, int *a)
{
InitB(s, a[0], a[1], a[2], a[3]);
}
int main()
{
int a[] = { 1, 2, 3, 4 };
struct B s;
InitBFromArray(&s, a);
}