Home > database >  What is the purpose of the reverse loop and where is the element being injected to the array
What is the purpose of the reverse loop and where is the element being injected to the array

Time:01-19

I came across a piece of code that do this:

arr = &some_array;
some_placeholder = array_push(arr);

// The loop:
for (i = arr->nelts - 1; i > 0; --i) {
    *((some_pointer *)arr->elts   i) = *((some_pointer *)arr->elts   i - 1);
}
*(some_pointer *)arr->elts = my_item;

What is the purpose of the loop?

I do not have a c knowledge, and I wonder what is this loops trying to do, and where is the my_item goes inside the array?

CodePudding user response:

Very short:

The loop copies each item from index i - 1 to index i. If the loop was not in reverse order, it would copy first item to every item.

Then it overwrites item at index 0 (now also copied to index 1) with my_item.


A more readable way to write the loop would be to use array indexing instead of plain pointer arithmetic. This is exactly equal code:

for (i = arr->nelts - 1; i > 0; --i) {
    (some_pointer *)arr->elts[i] = (some_pointer *)arr->elts[i-1];
}
(some_pointer *)arr->elts[0] = my_item;
  •  Tags:  
  • Related