[SOLVED] Best way to shift an array in C?


I have an array that holds a history of values, and when adding a new value, I need to shift all previous values one position to the left, to loose the oldest value and make room for the next.

I can think of two ways of doing this, by using memmove:

memmove(&arr[0], &arr[1], sizeof(arr) - sizeof(*arr));

Or by swapping the pointers:

for (i = 0; i != sizeof(arr) - 1; i++) {
   *(arr + i) = *(arr + i + 1);

Is there a performance difference between the two methods, and if not, which one would be advised?


They both have the same time complexity. Any other difference in performance would be due to specific circumstances, such as the CPU, the compiler, how memmove is implemented, and the size of the array, so you have to actually measure the performance each way and see what is best.

Answered By – Vaughn Cato

Answer Checked By – Mildred Charles (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *