`error: assignment to expression with array type` when trying to set struct member

`error: assignment to expression with array type` when trying to set struct member

我确定以前有人问过这个问题,但我找不到了。

考虑:

#include <stdlib.h>

struct Image {
    char* name;
    float transform[6];
};

int main() {
    float transform[6] = {0,0,0,0,0,0};
    struct Image *ex = calloc(1,sizeof(struct Image));
    ex->name="test";
    // ex->transform=transform; // causes error.
    return 0;
}

我当然收到:

test.c: In function 'main':
test.c:12:18: error: assignment to expression with array type
   12 |     ex->transform=transform;

所以我的问题是,有没有更甜的方法:

12c12,17
<     ex->transform=transform; // causes error.
---
>     ex->transform[0]=transform[0];
>     ex->transform[1]=transform[1];
>     ex->transform[2]=transform[2];
>     ex->transform[3]=transform[3];
>     ex->transform[4]=transform[4];
>     ex->transform[5]=transform[5];

谢谢!

您可以使用 <string.h> 头文件中的 memcpy() 函数。

int main()
{
    float transform[6] = {0,0,0,0,0,0};

    struct Image *ex = calloc(1,sizeof(struct Image));
    ex->name="test";

    memcpy(ex->transform ,transform , sizeof(ex->transform));
    free(ex);
    return 0;
}

尽管您可以使用 memcpy(在 <string.h> 中声明)来复制数组:

float transform[6] = {0,0,0,0,0,0};
struct Image *ex = calloc(1, sizeof *ex);
ex->name = "test";
memcpy(ex->transform, transform, sizeof ex->transform);

另一种选择是使用复合文字来分配完整的结构:

struct Image *ex = calloc(1, sizeof *ex);
*ex = (struct Image) { "test", { 0, 0, 0, 0, 0, 0 } };

当然,不需要将零元素分配给数组,因为它已被 calloc 设置为零,但您可以将以上内容与其他值一起使用。