I want to copy an int
array to another int
array. They use the same define for length so they'll always be of the same length.
What are the pros/cons of the following two alternatives of the size parameter to memcpy()
?
memcpy(dst, src, ARRAY_LENGTH*sizeof(int));
or
memcpy(dst, src, sizeof(dst));
Will the second option always work? Regardless of the content?
One thing that favors the last one is that if the array were to change, it'll be some house-keeping to update the memcpy()
's.
As long as dst
is declared as an array with a size, sizeof
will return the size of that array in bytes:
int dst[ARRAY_LENGTH];
memcpy( dst, src, sizeof(dst) ); // Good, sizeof(dst) returns sizeof(int) * ARRAY_LENGTH
If dst
just happens to be a pointer to the first element of such an array (which is the same type as the array itself), it wont work:
int buffer[ARRAY_LENGTH];
int* dst = &buffer[0];
memcpy( dst, src, sizeof(dst) ); // Bad, sizeof(dst) returns sizeof(int*)