When working with arrays of the same length, consider creating a structure which only contains an array so that it is easier to copy the array by simply copying the structure into another one.
The definition and declaration of the structure would be like this:
typedef struct {
char array[X]; /* X is an arbitrary constant */
} Array;
Array array1;
Then, perform the copy by simply doing:
Array array2;
array2 = array1;
I have found that this as the fastest way of copying an array. Does it have any disadvantage?
Edit: X is an arbitrary constant, let’s say 10. The array is not a variable length array.
This works fine, but since
Xmust be defined at compile-time it is rather inflexible. You can get the same performance over an array of any length by usingmemcpyinstead. In fact, compilers will usually translatearray2 = array1into a call tomemcpy.As mentioned in the comments, whether direct assignment gets translated into a
memcpycall depends on the size of the array amongst other compiler heuristics.