如何增加一个指针地址和指针的值? [英] How to increment a pointer address and pointer's value?
问题描述
让我们假定,
int *p;
int a = 100;
p = &a;
什么将以下code,实际上又是如何?
What will the following code will do actually and how?
p++;
++p;
++*p;
++(*p);
++*(p);
*p++;
(*p)++;
*(p)++;
*++p;
*(++p);
我知道,这是一种凌乱的编码方面,但我想知道我们什么时候code这样会有什么实际发生。
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.
请注意:让我们假设 A = 5120300
的地址,它存储在指针 P
地址是 3560200
。现在,将 P和价值;一个
每个语句执行后?
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?
推荐答案
首先,*运营商需要precedence了++运算符,和()的经营者借此precedence胜于一切。编辑(事情比这更复杂,见底编辑)
First, the * operator takes precedence over the ++ operator, and the () operators take precedence over everything else. EDIT(things are more complicated than that, see bottom edit)
二,数++运算符是一样的号码++运算符,如果你不将其分配给什么。所不同的是++返回数号码,然后递增第一号和++数目的增量,然后返回它。
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.
三,通过增加指针的值,你的sizeof的递增它的内容,那就是你递增它,就好像你在一个数组迭代。
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.
所以,总括起来:
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
由于有很多在这里的情况下,我可能已经取得了一些错误,请纠正我,如果我错了。
As there are a lot of cases in here, I might have made some mistake, please correct me if I'm wrong.
编辑:
所以,我错了,precedence有一点比我写的更复杂,查看这里:
HTTP://en.cp$p$pference.com / W / CPP /语言/ operator_ precedence
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
这篇关于如何增加一个指针地址和指针的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!