search

Home  >  Q&A  >  body text

c++ - 我用指针对数组赋值的操作哪里错了?

#include <iostream>

using namespace std;

int main()
{
    int* p;
    int arr[10];
    p = arr;
    
    for( int i = 0; i <10; i++)
    {
        //arr[i] = i;   //这句可以得到预计的结果
        //*(p + i) = i  //这句也可以
        *(p++) = i;   //这句为什么不行
    }

    for(int i = 0; i < 10; i++)
    {
        cout << *(p++) <<endl;  //这句可以`请输入代码`
    }
}
PHPzPHPz2807 days ago413

reply all(1)I'll reply

  • 高洛峰

    高洛峰2017-04-17 13:18:27

    When your first for loop ends, p already points to the last element of the array. This is completely out of bounds when using cout.

    reply
    0
  • Cancelreply