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);
dest ;
memcpy(dest, src2, 2);
dest ;
dest ;
How to do multiple memcpy()
that increment the destination pointer for you?
CodePudding user response:
Write your own function.
for example generic for any size elements:
void *generic(void *dest, const void *src, const size_t elemsize, size_t nelems)
{
char *cptr = dest;
memcpy(dest, src, elemsize * nelems);
cptr = nelems * elemsize;
return cptr;
}
or as in your example (char size elements)
void *charSizeOnly(void *dest, const void *src, size_t nelems)
{
char *cptr = dest;
memcpy(dest, src, nelems);
cptr = nelems;
return cptr;
}
example usage:
mytype *dest;
mytype *src;
/* ... some code*/
/*it will copy and update the dest by 30 elements of type `mytype`*/
desyt = generic(dest, src, sizeof(*dest), 30);
CodePudding user response:
You could make a function:
void memcpy_auto_inc( void **pp_dest, void *src, size_t count )
{
memcpy( *pp_dest, src, count );
*pp_dest = ((char*)*pp_dest) count;
}
Now, instead of writing
memcpy(dest, src1, 1);
dest ;
memcpy(dest, src2, 2);
dest =2;
you can write:
memcpy_auto_inc( &dest, src1, 1);
memcpy_auto_inc( &dest, src2, 2);
However, I doubt that this is worth the effort.
If the name memcpy_auto_inc
is too long for you, then you can also specify a shorter name.