Best way to shift an array in C?

Maestro picture Maestro · Sep 2, 2013 · Viewed 19.1k times · Source

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?

Answer

Klas Lindbäck picture Klas Lindbäck · Sep 2, 2013

There is a faster option:

A circular buffer where insert, remove and read are all O(1).