Issue
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?
Solution
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;
Answered By - hyde Answer Checked By - David Goodson (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.