无法将数组分配给另一个

我尝试了不同的方法将数组指针复制到另一个,没有任何成功。 以下是我的尝试,以及相关的错误消息。

typedef long int coordinate; typedef coordinate coordinates[3]; void test(coordinates coord) { coordinates coord2 = coord; // error: invalid initializer coordinates coord3; coord3 = coord; // error: incompatible types when assigning to type 'coordinates' from type 'long int *' coord3 = (coordinates) coord; // error: cast specifies array type coord3 = (coordinate[]) coord; // error: cast specifies array type coord3 = (long int*) coord; // error: incompatible types when assigning to type 'coordinates' from type 'long int *' } 

我知道我可以使用typedef coordinate* coordinates; 相反,但它对我来说并不是很明确。

您无法在C中分配数组。使用memcpy将数组复制到另一个数组中。

 coordinates coord2; memcpy(coord2, coord, sizeof coord2); 

当数组按值传递时,它们会衰减为指针 。 解决这个问题的常见技巧是将固定大小的数组包装在struct ,如下所示:

 struct X { int val[5]; }; struct X a = {{1,2,3,4,5}}; struct X b; b = a; for(i=0;i!=5;i++) printf("%d\n",b.val[i]); 

现在,您可以按值将包装的数组传递给函数,分配它们,等等。

您的坐标需要初始化为指针

coordinates *coords2, *coords3;

尝试一下,然后分配。