如何增加指针地址和指针值?
让我们假设,
int *p;
int a = 100;
p = &a;
下面的代码实际上会做什么以及如何做?
p++;
++p;
++*p;
++(*p);
++*(p);
*p++;
(*p)++;
*(p)++;
*++p;
*(++p);
我知道,这在编码方面有点混乱,但我想知道当我们这样编码时实际上会发生什么。
注意:假设a=5120300
的地址存储在地址为3560200
的指针p
中。现在,p & 的值是多少?每条语句执行后的a?
Let us assume,
int *p;
int a = 100;
p = &a;
What will the following code actually do and how?
p++;
++p;
++*p;
++(*p);
++*(p);
*p++;
(*p)++;
*(p)++;
*++p;
*(++p);
I know, this is kind of messy in terms of coding, but I want to know what will actually happen when we code like this.
Note : Lets assume that the address of a=5120300
, it is stored in pointer p
whose address is 3560200
. Now, what will be the value of p & a
after the execution of each statement?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
首先,++ 运算符优先于 * 运算符,并且 () 运算符优先于其他所有运算符。
其次,如果您没有将 ++number 运算符分配给任何内容,则 ++number 运算符与 number++ 运算符相同。区别是number++返回number然后将number递增,而++number先递增然后返回。
第三,通过增加指针的值,您可以按其内容的大小来增加它,也就是说,您可以像在数组中迭代一样来增加它。
所以,总结一下:
由于这里有很多案例,我可能犯了一些错误,如果我错了,请纠正我。
编辑:
所以我错了,优先级比我写的要复杂一点,在这里查看:
http://en.cppreference.com/w/cpp/language/operator_precedence
First, the ++ operator takes precedence over the * operator, and the () operators take precedence over everything else.
Second, the ++number operator is the same as the number++ operator if you're not assigning them to anything. The difference is number++ returns number and then increments number, and ++number increments first and then returns it.
Third, by increasing the value of a pointer, you're incrementing it by the sizeof its contents, that is you're incrementing it as if you were iterating in an array.
So, to sum it all up:
As there are a lot of cases in here, I might have made some mistake, please correct me if I'm wrong.
EDIT:
So I was wrong, the precedence is a little more complicated than what I wrote, view it here:
http://en.cppreference.com/w/cpp/language/operator_precedence
检查程序,结果如下,
checked the program and the results are as,
以下是各种“仅打印”建议的实例。我发现它很有启发。
它返回
我将指针地址转换为int,以便可以轻松比较它们。
我是用GCC编译的。
The following is an instantiation of the various "just print it" suggestions. I found it instructive.
It returns
I cast the pointer addresses to
int
s so they could be easily compared.I compiled it with GCC.
关于“如何增加指针地址和指针的值?”我认为
++(*p++);
实际上定义良好并且可以满足您的要求例如:它不会在序列点之前两次修改同一事物。虽然对于大多数用途来说,我认为这不是一个好的风格——对我来说,它有点太神秘了。
With regards to "How to increment a pointer address and pointer's value?" I think that
++(*p++);
is actually well defined and does what you're asking for, e.g.:It's not modifying the same thing twice before a sequence point. I don't think it's good style though for most uses - it's a little too cryptic for my liking.