简体   繁体   English

如何使用Memcpy初始化结构体中的数组

[英]How use memcpy to initialize array in struct

I have simple struct: 我有简单的结构:

typedef struct{
double par[4];
}struct_type;

I have also initialize function for it where one argument is a 4 elements array. 我也为其初始化函数,其中一个参数是4个元素的数组。 How properly use memcpy to initalize array in struct? 如何正确使用memcpy在struct中初始化数组? Something like this don't work for me: 这样的事情对我不起作用:

 struct_type* init_fcn(double array[4]){

 struct _type* retVal;
 retVal->par=malloc(sizeof(double)*4);
 memcpy(retVal->par,&array);

return retVal;
}

I can init values one by one but i thnik memcpy will be better and faster. 我可以一一初始化值,但我会更好,更快。 Do You have any ideas how to proper do it? 您是否有适当的想法?

If you want to return a pointer to a new object of type struct_type , then you should create exactly such an object, ie use malloc(sizeof(struct_type)) instead of allocating space for any members directly. 如果要返回指向类型为struct_type的新对象的struct_type ,则应完全创建此类对象,即使用malloc(sizeof(struct_type))而不是直接为任何成员分配空间。 So your code could look as follows: 因此,您的代码可能如下所示:

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM