Is this a correct way to copy elements from array origin to array location?
#include <stdio.h>
void copy(const int *origin, int *location, int n){
int i;
for(i=0;i<n;i++){
location[i]=origin[i];
}
}
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It only takes a minute to sign up.
Sign up to join this communityIs this a correct way to copy elements from array origin to array location?
#include <stdio.h>
void copy(const int *origin, int *location, int n){
int i;
for(i=0;i<n;i++){
location[i]=origin[i];
}
}
#include <stdio.h>
This function doesn't use anything from <stdio.h>
, so don't waste the compiler's time by including it.
void copy(const int *origin, int *location, int n){
I would put the destination argument first, to be consistent with Standard Library functions such as memcpy
. And change n
to be a size_t
, so it will work with any array.
int i; for(i=0;i<n;i++){
We can reduce the scope of i
, by declaring it in the control expression: for (int i = 0; i < n; ++i)
.
location[i]=origin[i];
We ought to tell the compiler (with restrict
) that the arrays don't overlap.
I think it's simpler just to forward to memcpy()
:
#include <string.h>
void copy(int *restrict dest, int const *restrict origin, size_t count)
{
memcpy(dest, origin, sizeof *dest * count);
}
But that's so simple that I don't think we want a separate function for it (particularly with such a broad name).
memcpy()
like and return dest
;
\$\endgroup\$
Feb 16 at 18:31
<xxx.h>
from .c files. Too much maintenance - so I'd rather waste compiler's time than mine. Some development environments do automate this though.
\$\endgroup\$
Feb 16 at 18:33
memcpy(dst, src, n)
. \$\endgroup\$