C ++指针和算术

时间:2015-04-27 03:45:00

标签: c++ pointers math

#include <iostream>
using namespace std;
int main(int argc, _TCHAR* argv[])
{
    int a[10]={0,1,2,3,4,5,6,7,8,9};
    int *aptr;
    aptr = &a[0];
    a[2] = a[2] + 3;
    a[3] = a[5] + a[4];
    aptr++;
    (*aptr)--;
    (*(++aptr))++;
    cout << a[1] << a[2] << a[3] << a[4] << *aptr << endl;
}

手头的问题是假设上面的代码编译,我应该得到06946的输出。任何人都可以通过代码为我?我不太明白代码是如何到达输出的?

3 个答案:

答案 0 :(得分:1)

int main(int argc, _TCHAR* argv[])
{
    int a[10]={0,1,2,3,4,5,6,7,8,9};    
    // a is an array of 10 ints.
    int *aptr;
    // aptr is a pointer to int.
    aptr = &a[0];
    // aptr points to the 1st element of a array. i.e. a[0]
    a[2] = a[2] + 3;
    // You add 3 to a[2], i.e. third element of array to get '5' and put it back in a[2].
    // So 'a' will be {0,1,5,3,4,5,6,7,8,9}
    a[3] = a[5] + a[4];
    // You take 6th and 5th elements, add them and put it in 4th element.
    // So 'a' will be {0,1,5,9,4,5,6,7,8,9}
    aptr++;
    // aptr pointer is incremented so now it points to 2nd element of a array i.e a[1].
    (*aptr)--;
    // aptr pointer is first dereferenced to get a[1], which is then decremented.
    // So 'a' will be {0,0,5,9,4,5,6,7,8,9}
    (*(++aptr))++;
    // aptr pointer is incremented first so now it points to 3rd element i.e. a[2].
    // aptr pointer is then dereferenced to get a[2], which is then incremented.
    // So 'a' will be {0,0,6,9,4,5,6,7,8,9} and aptr points to a[2]
    cout << a[1] << a[2] << a[3] << a[4] << *aptr << endl;
   // So it should print 06946
}

答案 1 :(得分:0)

让我们回顾一下代码中的每一步:

int a[10]={0,1,2,3,4,5,6,7,8,9}; //initial state of your array
int *aptr;
aptr = &a[0]; //pointer on the first element
a[2] = a[2] + 3; //a[2]=5 now
a[3] = a[5] + a[4]; //a[3]=9 now
aptr++; //pointer on the second element
(*aptr)--; //decrement the value pointed by the pointer: a[1]=0 now
(*(++aptr))++; 
//first increment the pointer the increments the value pointed by the new pointer so a[2]=6 now

请注意,最后一行可能具有不同的行为,因为它包含后缀和前缀增量,但由于它们位于两个不同的值上,因此它应该是安全的。

答案 2 :(得分:-1)

int a[10]={0,1,2,3,4,5,6,7,8,9};
int *aptr;
aptr = &a[0];

aptr引用了a[0]

a[2] = a[2] + 3;
//  a[2] == 5
a[3] = a[5] + a[4];
// a[3] == 9
aptr++;

移动aptra[1]

的引用
(*aptr)--;

aptr之前的*现在意味着您正在修改它引用的值的任何值。因此aptr指向a[1],我们会将其VALUE减少1.因此a[1]等于0。

(*(++aptr))++;

让我们打破这个。 (++aptr)表示我们可以将指针从a[1]移动到a[2](*(++aptr))现在说让我们关注aptr的值。我们现在知道a[2] == 5。最后(*(++aptr))++说让我们将该值增加1.所以a[2] == 6。请记住*aptr NOW也因此等于6。

cout << a[1] << a[2] << a[3] << a[4] << *aptr << endl;

因此我们确定a[1]的值已更改为0。 由于简单的数学运算,我们确定了a[2] == 6a[3]9的原因 最后*aptr == 6,因为这是我们对指针执行的最后一个操作。

我希望这能帮助你理解你的运动。