c++ - c语言指针运算问题
迷茫
迷茫 2017-04-17 14:00:01
0
8
353

c 指针运算问题?修改
一、代码:

int a[]={1,2,3,4,5};
int *p;
p=a;
*(p++)=10;
int i;
for (i=0; i<sizeof(a)/sizeof(int); i++) {
printf("a[%d]=%d\n",i,a[i]);
}

输出:
a[0]=10
a[1]=2
a[2]=3
a[3]=4
a[4]=5
二、问题
明明指针往下移了,为什么a[0]=10,而不是a[1]=10?

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(8)
巴扎黑

p++
++ followed by
is equivalent to

*(p)=10;
p++

is different from ++p

黄舟

(p++)=10 (p++) returns the subscript of 0, so the result is like this. In fact, your sentence is equivalent to p++, and the result is the same

黄舟

p++ will return the value before it is incremented, and p will not be incremented until the end of the expression evaluation phase. Here *p++ can be regarded as a subexpression.

小葫芦

P++ If you are not familiar with it, use it sparingly. It won’t save much cost. It’s a simple matter of calculating first and then assigning a value, and first assigning a value and then calculating.

Peter_Zhu
#include <stdio.h>
int main()
{

    int a[]={1,2,3,4,5};
    int *p;
    p=a;
    *(p+1)=10;
    p++;
    int i;
    for (i=0; i<sizeof(a)/sizeof(int); i++) {
        printf("a[%d]=%d\n",i,a[i]);
    }
}
Peter_Zhu

p++ and p are exactly the same, ++p is equal to (p+1), but no matter what, these two things exist in the subsequent code p=p+1. (If you still don’t understand, read the book yourself)

左手右手慢动作

There is a simple method for you to understand: you can print p, p++ in sequence ((p++) still takes the scalar value p++, or here you can output &((p++)) ) and p. After looking at the results, you will understand that the memory address of *(p++) is still p, and then it becomes p+1

Ty80

The difference between "prefix++" and "suffix++", classic test questions in c/c++

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