为什么我的增量没有发生在最后一个元素上

Why my incrementation not happening to the last element?

本文关键字:最后一个 元素 我的 为什么      更新时间:2023-10-16

这是我的代码,试图使用指针将元素增加1。我的最后一个元素没有增加。你能告诉我为什么吗

#include<iostream>
using namespace std;
void print_all( int *start,  int *stop)
 { 
  int *curr = start;
  while(curr != stop)
      {
    ++(*curr);
    ++curr;
    cout<< "n"<<"content at address "<<curr<<" got incremented to "<< *curr<<"n";    
      }
}

 int main()
  { 
   int a[] = {3,4,5};
   print_all(a, a+3);
   return 0;
  }

输出:

content at address 0x7ffe3ded3eb4 got incremented to 4
content at address 0x7ffe3ded3eb8 got incremented to 5
content at address 0x7ffe3ded3ebc got incremented to 0

让我们用循环的第一次迭代来解释这一点:

  1. 条件计算为true,执行主体
  2. *curr处的值增加一
  3. curr递增1以指向下一个数组成员
  4. 打印下一个数组成员第一个成员永远不会被打印

0是未定义行为的实例;虽然仅指向数组之外的一个是定义良好的,但访问该地址的值是未定义的。

3rd步骤做得太早。将第3个rd与第4个交换,您就可以了。