c - ANSI C/C89 结构体到 int array[]

标签 c arrays struct c89

是否有一种有效的方法将结构分配/转换为数组,反之亦然?

我的结构如下:

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/

相关文章:

c - c中结构体返回值出现逻辑错误

javascript - 使用外部数据输入更新数组中的对象时提高性能

ART中的Android自修改代码

c - 如何解释反三角函数(和 sqrt)函数(在 C 中)的浮点运算中的舍入误差?

复数 (complex.h) 和明显的精度滞后

java - 哈希是合适的解决方案吗?我是不是太复杂了?

python - 如何访问 NumPy 多维数组的第 i 列?

c++ - C++ 中的嵌套结构

c - 如何在不创建变量的情况下将项目添加到结构中

c - 无法理解结构的内存分配