如何增加指针地址和指针的值?

让我们假设,

int *p; int a = 100; p = &a; 

下面的代码将会做什么以及如何做?

 p++; ++p; ++*p; ++(*p); ++*(p); *p++; (*p)++; *(p)++; *++p; *(++p); 

我知道,在编码方面这是一团糟,但我想知道当我们这样编码时会发生什么。

注意:假设a=5120300的地址存储在地址为3560200指针p 。 现在,在执行每个陈述之后, p & a的价值是多less?

首先,*运算符优先于++运算符,()运算符优先于其他所有。 编辑(事情比这更复杂,请参阅底部编辑)

其次,++数字运算符与数字++运算符相同,如果你不把它们分配给任何东西。 不同之处在于数字++返回数字,然后递增数字,++数字递增,然后返回它。

第三,通过增加一个指针的值,你可以通过增加内容的大小来增加它,那就是你正在递增它,就好像你正在迭代一个数组。

所以,总结一下:

 ptr++; // Pointer moves to the next int position (as if it was an array) ++ptr; // Pointer moves to the next int position (as if it was an array) ++*ptr; // The value of ptr is incremented ++(*ptr); // The value of ptr is incremented ++*(ptr); // The value of ptr is incremented *ptr++; // Pointer moves to the next int position (as if it was an array). But returns the old content (*ptr)++; // The value of ptr is incremented *(ptr)++; // Pointer moves to the next int position (as if it was an array). But returns the old content *++ptr; // Pointer moves to the next int position, and then get's accessed, with your code, segfault *(++ptr); // Pointer moves to the next int position, and then get's accessed, with your code, segfault 

由于这里有很多情况,我可能会犯一些错误,如果我错了,请纠正我。

编辑:

所以我错了,优先级比我写的要复杂一些,在这里查看: http : //en.cppreference.com/w/cpp/language/operator_precedence

检查了程序,结果如下,

 p++; // use it then move to next int position ++p; // move to next int and then use it ++*p; // increments the value by 1 then use it ++(*p); // increments the value by 1 then use it ++*(p); // increments the value by 1 then use it *p++; // use the value of p then moves to next position (*p)++; // use the value of p then increment the value *(p)++; // use the value of p then moves to next position *++p; // moves to the next int location then use that value *(++p); // moves to next location then use that value 

关于“如何递增指针地址和指针的值?” 我认为, ++(*p++); 实际上已经很好的定义了,并且按照你的要求去做,例如:

 #include <stdio.h> int main() { int a = 100; int *p = &a; printf("%p\n",(void*)p); ++(*p++); printf("%p\n",(void*)p); printf("%d\n",a); return 0; } 

在一个序列点之前不会两次修改相同的东西。 虽然对于大多数用途来说,我认为这不是一种好的风格 – 对我的喜好来说有点太神秘了。