Is there a method of using memcpy (or similar) to copy from one circular array into another, but with an offset? I can do it with loops, but I want to do it more fasterer and betterer. Obviously 'circular' isn't a thing with memory, but I hope you get what I mean.
Cheers all.
This is what I want to achieve but without having to use a For;;loop
uint8_t array1[SIZE];
uint8_t array2[SIZE];
uint8_t offset = SOME_OFFSET;
uint8_t offsetAdj;
for (uint8_t index = 0; index < SIZE; index )
{
offsetAdj = offset index;
if (offsetAdj >= SIZE)
offsetAdj -= SIZE;
array2[offsetAdj] = array1[index];
}
CodePudding user response:
That's a std::rotate_copy
that you have implemented with your code.
uint8_t array1[SIZE];
uint8_t array2[SIZE];
uint8_t offset = SOME_OFFSET;
std::rotate_copy( std::begin(array1),
std::begin(array1) offset,
std::end (array1),
std::begin(array2) );
Unlike memcpy
, std::rotate_copy
will also work on non-contiguous containers and containers of types that are not trivially copyable.
CodePudding user response:
Here is a simple working example
#include <stdio.h>
#include <string.h>
#include <stdint.h>
int main() {
uint8_t SIZE = 8;
uint8_t array1[SIZE];
uint8_t array2[SIZE];
uint8_t offset = 3;
uint8_t i = 0;
// Initialize the arrays with some values
for (i = 0; i < SIZE; i ) {
array1[i] = i;
array2[i] = 0;
}
// Copy the elements of array1 into array2 with an offset of 3
memcpy(&array2[offset], array1, SIZE - offset);
memcpy(array2, &array1[SIZE - offset], offset);
// Print the contents of array1 and array2 to verify the copy
for (i = 0; i < SIZE; i )
printf("%d ", array1[i]);
printf("\n");
for (i = 0; i < SIZE; i )
printf("%d ", array2[i]);
return 0;
}