C/C++ Does This 'for' Loop in C++ Cause an Error?

  • Thread starter Thread starter ineedhelpnow
  • Start date Start date
  • Tags Tags
    Loops
Click For Summary
The code snippet provided results in an error due to an out-of-bounds access. The loop iterates from 0 to the size of the array minus one, but the line `itemsList.at(i) = itemsList.at(i+1);` attempts to access an index that exceeds the array's bounds when `i` equals the last index. This leads to an attempt to access `itemsList.at(n)`, which is invalid, confirming that the loop will indeed result in an error.
ineedhelpnow
Messages
649
Reaction score
0
does this result in an error?

for (i = 0; i < itemsLast.size(); ++i)
{
itemsList.at(i) = itemsList.at(i+1);
}
 
Technology news on Phys.org
Counting begins at zero, so if you have an array with $n$ elements, the index value for the last element is therefore $n-1$. So, does the loop result in an error?
 
Yes
 
Learn If you want to write code for Python Machine learning, AI Statistics/data analysis Scientific research Web application servers Some microcontrollers JavaScript/Node JS/TypeScript Web sites Web application servers C# Games (Unity) Consumer applications (Windows) Business applications C++ Games (Unreal Engine) Operating systems, device drivers Microcontrollers/embedded systems Consumer applications (Linux) Some more tips: Do not learn C++ (or any other dialect of C) as a...

Similar threads

  • · Replies 14 ·
Replies
14
Views
3K
  • · Replies 22 ·
Replies
22
Views
3K
  • · Replies 2 ·
Replies
2
Views
1K
  • · Replies 11 ·
Replies
11
Views
728
  • · Replies 1 ·
Replies
1
Views
4K
  • · Replies 4 ·
Replies
4
Views
2K
  • · Replies 5 ·
Replies
5
Views
2K
  • · Replies 1 ·
Replies
1
Views
1K
  • · Replies 4 ·
Replies
4
Views
1K
  • · Replies 11 ·
Replies
11
Views
2K