是否有一种有效的方法将结构分配/转换为数组,反之亦然?
我的结构如下:
struct A {
int x, y;
}
struct B {
struct A start;
struct A end;
}
基本上它们包含开始和结束位置的 xy 坐标。
我需要有效地分配它们,但目前我只能这样做
/* 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]}};
我也可以使用复合文字,但当我使用标志 -Wall -pedantic -ansi 进行编译时,它会在 gcc 中发出警告
有没有办法将这 4 行赋值减少到只有一行,而不会收到带有上述标志的警告。
问候
编辑:固定复合文字语法
最佳答案
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);
}
关于c - ANSI C/C89 结构体到 int array[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25225092/