1

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?

12
  • Oh I see, memcpy also requires the size of the array, which is the same as the size given to malloc Commented Feb 12, 2017 at 18:07
  • sizeof(*double) is nonsense and will result in a compiler error. This isn't a minimal reproducible example Commented Feb 12, 2017 at 18:07
  • More like memcpy(retVal->par, array, sizeof(double)*4). Also in malloc you use sizeof(double) (size of one element) Commented Feb 12, 2017 at 18:08
  • 1
    @PaulStelian - Look closely at the bit I quoted. Where is the asterisk (*) located? Commented Feb 12, 2017 at 18:12
  • 1
    @PaulStelian - The edit history shows only the nonsense I quoted. But It was all edited away by now, so this discussion is moot. Commented Feb 14, 2017 at 11:36

1 Answer 1

4

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;
}
Sign up to request clarification or add additional context in comments.

4 Comments

@PSkocik: noticed right now and corrected it; thanks.
Thanks! It work for me. So is 'r->par' first value in par array and '&r-par' is adress of first element?
@ArkadiuszKuleta No. The first is the array, which in the context of a function call decays to the address of the first element, and the second is the address of the array, which is numerically the same. In this context, you can use r->par, &r->par, &r->par[0], and it doesn't matter which one you use.
@PSkocik: More accurately, r->par and &r->par[0] are the same type (double *) and value; &r->par is of type double (*)[4], though its value as a void * is the same as r->par etc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.