Basically I need to do multiple memcpy()
and I don't want to increment the destination pointer dst++;
after every memcpy()
call.. just wondering how to save some coding time.
memcpy(dest, src1, 1); // uint8_t
dest += 1;
memcpy(dest, src2, 2); // uint16_t
dest += 2;
memcpy(dest, src3, 1024); // uint8_t*
dest += 1024;
...
How to do multiple memcpy()
that increment the destination pointer for you?
You could make a function:
void memcpy_auto_inc( char **pp_dest, const void *src, size_t count )
{
memcpy( *pp_dest, src, count );
*pp_dest += count;
}
Now, assuming that dest
is of type char*
, instead of writing
memcpy( dest, src1, 1 );
dest += 1;
memcpy( dest, src2, 2 );
dest += 2;
memcpy( dest, src3, 1024 );
dest += 1024;
you can write:
memcpy_auto_inc( &dest, src1, 1 );
memcpy_auto_inc( &dest, src2, 2 );
memcpy_auto_inc( &dest, src3, 1024 );
However, I doubt that this is worth the effort, as it makes the code less clear and doesn't save you much typing, even if you select a much shorter name for the function than memcpy_auto_inc
.
EDIT:
On request of OP, I will provide additional information regarding restrict
and inline
optimizations:
The function memcpy_auto_inc
can be further optimized by changing the function prototype to use the restrict
type qualifier:
void memcpy_auto_inc( char *restrict *restrict pp_dest, const void *restrict src, size_t count )
It would also be possible to add the inline
function specifier. However, in my opinion, this is not necessary, as it is unlikely that this will result in increased run-time performance. You can generally rely on the compiler's optimizer to make the decision on whether it is appropriate to inline a function.
This topic is further discussed in this question:
When to use inline function and when not to use it?
However, that question is 12 years old and compiler's optimizers have improved significantly since then, so there is now even less reason to use the inline
keyword.