Search code examples
cpointersperformancedereferencedecrement

Combined dereference and decrement in C


I need as efficient a means as possible to shift the contents of an array. I need to shift the contents of each array location one to the right and ignore the first one, so that I can write a new value there.

Here's what I have:

#define LENGTH 5

int myArray[LENGTH] = {1, 2, 3, 4, 5};

int *pa = myArray + (LENGTH - 1);

for (ushort i = 5; i > 0; i--) {
    *pa = *(pa - 1);
    pa--;
}

What I'd like to do is combine the two lines of the for loop into a single operation. Something like:

*pa = *(pa--);

The result of this is undefined, however. Am I stuck with what I'm already using?

EDIT: I should have clarified that this is not the actual code I'm using, just a quick example to demonstrate the construct that I was after.


Solution

  • If you really need to do this, memmove is probably going to be your best choice.

    If at all possible, however, you're better off avoiding it completely. Instead of shifting the current contents to make room for the new item, just keep a pointer to the "oldest" spot in the array. When you need to add a new item, do something like *new_pos++ = new_item;.

    When you need to read your data, you'll start from new_pos+1 and read through for the next 5 items, but each time you increment you'll do % LENGTH, so when you reach the end of the array, it "wraps around" to the beginning.