Yes, you can use memcpy, with a few caveats:
- The layout of the array and structure are identical, meaning that the compiler does not align either the items in the array or entries in the structure.
- The memory associated with the struct and array are identical in size.
- You are not concerned with portability to other architectures (which may change the answers to #1 and/or #2).
- This is not an ideal programming technique as it has some potential pitfalls, as noted above).
If after the above you still want to do this, the following code should do the trick:
/* NOTE: sizeof(ComplexStructVec) === sizeof(ComplexArrVec) */
memcpy((void *) ComplexStructVec,
(void *) ComplexArrVec,
sizeof(ComplexStructVec)*NumEl);
What this does is, since you are using vectors (arrays) in both cases, you have the address of them by using just their names. memcpy
defines the destination and source addresses as void *
, so I cast the arguments. The number of bytes to copy is the size, in bytes, of the structure or array (see NOTE) times the number of entries in the vector. The (void *)
cast may not be required. It depends upon the compiler, the language standard level, and other compile time qualifiers.
Also note, I intentionally did not have a place for the return value, which is a pointer to the destination. If you want this information, be careful, as saving it to ComplexStructVec
may cause either compiler (or worse case run-time) issues, depending on how it was allocated (by the compiler or during run-time).
A more complete example:
void copy(ComplexStruct* ComplexStructVec, ComplexArr* ComplexArrVec)
{
unsigned NumEl = 1000;
memcpy(ComplexStructVec, ComplexArrVec, sizeof(ComplexStruct)*NumEl);
}