PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, July 10, 2022

[FIXED] What is the purpose of the reverse loop and where is the element being injected to the array

 July 10, 2022     c, reference     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing