Best way to shift an array in C?

21.1k views Asked by At

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?

4

There are 4 answers

1
Vaughn Cato On BEST ANSWER

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.

0
pkacprzak On

You can use the FIFO Queue implemented as a linked list or as an array. From your description, it's the most straightforward solution.

0
Farouq Jouti On

I don't think that an array is the best way to do this , try using a linked list and you wont have this problem.

0
Klas Lindbäck On

There is a faster option:

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