我确定以前有人问过这个问题,但我找不到。
考虑:
#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];
谢谢!
最佳答案
尽管您可以使用 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
设置为零。 , 但您可以将以上内容与其他值一起使用。
关于c - 尝试设置结构成员时为 `error: assignment to expression with array type`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57934877/