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. How properly use memcpy to initalize array in 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, i.e. use malloc(sizeof(struct_type))
instead of allocating space for any members directly. 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;
}