0

我需要将一个数组转换为一个具有 void* 元素的结构,然后返回另一个数组:

unsigned short array[size];
//do something to the array

typedef struct ck{

void * arg1;
void * arg2;
void * arg3;


} argCookie;


argCookie myCookie;

myCookie.arg2=malloc(sizeof(array));//alloc the necessary space
memcpy(myCookie.arg2,&array,sizeof(array));//copy the entire array there


//later....


unsigned short otherArray[size];
otherArray=*((unsigned short**)aCookie.arg2);

碰巧这最后一行不会编译......为什么会这样?显然我在某个地方搞砸了......

谢谢你。

4

3 回答 3

1

您不能分配给数组。代替

otherArray=*((unsigned short**)aCookie.arg2);

如果您知道尺寸,请再次使用memcpy

memcpy(&otherArray, aCookie.arg2, size*sizeof(unsigned short));

如果你不知道大小,那你就不走运了。

于 2012-10-19T11:51:41.733 回答
1

您不能通过为其分配指针来复制数组,数组不是指针,并且您不能分配给数组,您只能分配给数组的元素。

您可以使用 memcpy() 复制到您的数组中:

//use array, or &array[0] in memcpy,
//&array is the wrong intent (though it'll likely not matter in this case
memcpy(myCookie.arg2,array,sizeof(array));

//later....

unsigned short otherArray[size];
memcpy(otherArray, myCookie.arg2, size);

假设您知道size,否则您还需要将大小放入其中一个 cookie 中。根据您的需要,您可能不需要复制到otherArray,只需直接使用 cookie 中的数据:

unsigned short *tmp = aCookie.arg2;
//use `tmp` instead of otherArray.
于 2012-10-19T11:54:03.507 回答
0
unsigned short* otherArray = (unsigned short*)aCookie.arg2

然后你可以使用otherArray[n]来访问元素。当心超出范围的索引。

于 2012-10-19T11:55:25.097 回答