Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ember.js/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 将void*转换为数组_C_Arrays_Malloc_Memcpy - Fatal编程技术网

C 将void*转换为数组

C 将void*转换为数组,c,arrays,malloc,memcpy,C,Arrays,Malloc,Memcpy,我需要转换一个数组,将其放置在具有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 necessa

我需要转换一个数组,将其放置在具有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);
碰巧这最后一行无法编译。。。 为什么呢?显然我在什么地方搞砸了


谢谢。

您不能分配给数组。而不是

otherArray=*((unsigned short**)aCookie.arg2);
如果您知道尺寸,只需再次使用
memcpy

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

如果你不知道数组的大小,那你就倒霉了。

你不能通过指定一个指针来复制数组,数组不是指针,你不能指定给数组,只能指定给数组的元素

您可以使用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);
这假设您知道
大小
,否则您也需要将大小放入一个cookie中。 根据需要,您可能不需要复制到
otherArray
,只需直接使用cookie中的数据即可:

unsigned short *tmp = aCookie.arg2;
//use `tmp` instead of otherArray.

然后可以使用
otherArray[n]
访问元素。小心越界索引。

如果要将
aCookie.arg2
复制到
otherArray
中,请再次使用
memcpy
unsigned short* otherArray = (unsigned short*)aCookie.arg2