不确定此循环的条件(指针算术)

Unsure of the condition for this loop (Pointer arithmetic)

本文关键字:指针 条件 循环 不确定      更新时间:2023-10-16

所以我应该通过评论中的要求编辑一堆代码。我已经得到了大部分,但有一部分特别让我卡住了。它像原来那样循环,但我不知道循环的条件应该是什么,不管我放什么,最后都会崩溃。我想是尺寸为?但我试过的都没用。任何帮助将不胜感激!

原始:

int main()
{
const string ID_BASE = "56-123-";
// CHANGE STATIC ARRAY INTO DYNAMIC ARRAY.
const int NUM_PRODUCTS = 5;
Product products[NUM_PRODUCTS];
int i;
//cout << "Enter number of toys: ";
//cin >> numProducts;
   ....Code to fill products...
//ALTER LOOP TO USE ONLY POINTER OPERATIONS
// (NO SUBSCRIPTS).
for (i = 0; i < numProducts; i++)
{
    show(products[i]);
}

我的变化:

int main()
{
const string ID_BASE = "56-123-";
// CHANGE STATIC ARRAY INTO DYNAMIC ARRAY.
int numProducts;
Product *products;
int i;
cout << "Enter number of toys: ";
cin >> numProducts;
products = new Product[numProducts];
...Code to fill products...
//ALTER LOOP TO USE ONLY POINTER OPERATIONS
// (NO SUBSCRIPTS).
for (Product *prodP = products;          ; *prodP++)
{
    show(*prodP);
}

条件:
prodP !=products+numProducts;

Do it iterator style:

auto begin = products;
auto end = products + numProducts;
for( auto itr=begin; itr!=end; ++itr )
{
    show(*itr);
}

也许我在这里错过了一些东西,但是修改后的循环何时结束??

for (Product *prodP = products;          ; *prodP++)
{
    show(*prodP);
}

只有有限的元素,我认为你超出了数组。