Arkadiusz Kuleta
Arkadiusz Kuleta

Reputation: 13

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. 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?

Upvotes: 1

Views: 2243

Answers (1)

Stephan Lechner
Stephan Lechner

Reputation: 35154

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

Upvotes: 4

Related Questions