c++ - 我用指针对数组赋值的操作哪里错了?
PHPz
PHPz 2017-04-17 13:16:27
0
1
411
#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;  //这句可以`请输入代码`
    }
}
PHPz
PHPz

学习是最好的投资!

reply all(1)
小葫芦

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template