C ++中的前/后增量指针

时间:2015-12-10 00:54:30

标签: c++ pointers increment post-increment pre-increment

*(P1 ++)

int array[10] = {1,2};
int *p1 = array;
*p1=24;
*p1= *(p1++);
for (int i : array)
    cout << i << " ";

输出为24 24

*(++ P1)

int array[10] = {1,2};
int *p1 = array;
*p1=24;
*p1= *(++p1);
for (int i : array)
    cout << i << " ";

输出为24 2

看起来这与使用值增量完全相反。有人能解释一下这里发生了什么吗?谢谢!

3 个答案:

答案 0 :(得分:2)

There is an undefined behavior in

*p1 = *(p1++);

because, quoting §1.9/15:

If a side effect on a scalar object is unsequenced relative to either another side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined.

Side effect here is an increment of p1 and value computation is a computation of address using p1.

So you shouldn't rely on the exact outcome of your examples.

答案 1 :(得分:1)

*p1= *(p1++);

This just doesn't make sense. The semantic meaning of this operation is different depending on which side of the = is evaluated first. So there's no way you can make any sense out of it.

答案 2 :(得分:-1)

对于*(p1 ++):

*p1 = *(p1++)

p1++会将p1增加到指向数组中的索引1,并返回先前的p1值(索引0)。因此*(p1++)将返回24,*p1现在将等于2. *p1然后被指定返回值(24),因此数组将为{24,24}

for *(++ p1):

*p1 = *(++p1)

++p1会将p1增加为指向数组中的索引2,并返回当前值p1(索引1)。因此*(++p1)将返回2,*p1现在将等于2. *p1然后被赋予返回值(2),这是索引为p1(1)的原始值,所以数组将保持{24,2}