如何使用memcpy初始化以struct
阵列I具有简单的结构:如何使用memcpy初始化以struct
typedef struct{
double par[4];
}struct_type;
我还初始化函数为其,其中一个参数是一个4个元素的数组。如何正确使用memcpy initalize array in struct?这样的东西不适合我:
struct_type* init_fcn(double array[4]){
struct _type* retVal;
retVal->par=malloc(sizeof(double)*4);
memcpy(retVal->par,&array);
return retVal;
}
我可以初始化值,但我thnik memcpy会更好,更快。你有什么想法如何正确做到这一点?
如果你想返回一个指向struct_type
类型的新对象的指针,那么你应该创建一个确切的对象,即使用malloc(sizeof(struct_type))
而不是直接为任何成员分配空间。所以,你的代码可能如下所示:
struct_type* init_fcn(double array[4]){
struct_type* retVal;
retVal = malloc(sizeof(struct_type));
if (retVal) {
memcpy(retVal->par,array,sizeof(retVal->par));
}
return retVal;
}
sizeof(array)也是错的 – PSkocik
@PSkocik:现在注意并纠正它;谢谢。 –
谢谢!它适合我。所以'par- par'是par数组中的第一个值,'&r-par'是第一个元素的地址? –
哦,我看到,MEMCPY也需要数组的大小,这是一样的给予的malloc大小 –
'的sizeof(*双)'是无稽之谈,并会导致在编译器错误。这不是[mcve] – StoryTeller
更像'memcpy(retVal-> par,array,sizeof(double)* 4)'。另外在malloc中,你可以使用'sizeof(double)'(一个元素的大小) –