[英]How can i understand &*(x+i)?
This is c++ code:这是 C++ 代码:
x[5]={1,2,3,4,5};
&x[i]==&*(x+i)==x+i;
as for &*(x+i)
,in my opinion, *(x+i)
is a rvalue ,why use &
.至于&*(x+i)
,在我看来, *(x+i)
是一个右值,为什么使用&
。 why?为什么?
This line &x[i]==&*(x+i)==x+i;
这一行&x[i]==&*(x+i)==x+i;
shell show you 3 different ways on getting the address of an specific element of an array. shell 向您展示了获取数组特定元素地址的 3 种不同方法。
In your case there is an array x
which stores 5 values.在您的情况下,有一个数组x
存储 5 个值。 The first thing probaly looks kind of familiar to you.第一件事对你来说可能看起来有点熟悉。 x[i]
will get the i
-th element of the x
and by using the address-of-operator you will get the address of the i
-th element of. x[i]
将得到i
的第的元素x
,并通过使用地址的运营商,您将获得的地址, i
的个元素。
Let's go on to the third statement x+i
.让我们继续第三个语句x+i
。 Since x
is actually just a pointer pointing to the adress of the first element of the actual array in your storage you can get the adress of other elements by adding an offset to x
.由于x
实际上只是指向存储中实际数组的第一个元素的地址的指针,因此您可以通过向x
添加偏移量来获取其他元素的地址。 However since you're working with x
' address you wont get the value of the 'offsetted' element but its address.但是,由于您使用的是x
' 地址,因此您不会获得 'offsetted' 元素的值,而是其地址。 To get the value you need to derefence the address by using the magical *
.要获得该值,您需要使用神奇的*
取消对地址的引用。 So if &x[i]
gets the adress of the i
th element and x+i
does the same, *(x+i)
will do the same thing as x[i]
.所以如果&x[i]
得到第i
个元素的地址并且x+i
做同样的事情, *(x+i)
将做与x[i]
相同的事情。 It will get the i
th value of x
.它将获得x
第i
个值。
No you know what the adress-of-operater &
and the derefencing-operator *
.不,您知道操作符的地址&
和取消引用操作符*
。 Theirefore the second statement is fairly simple.因此,第二个语句相当简单。 (x+i)
will get the address of the i
th element. (x+i)
将获得第i
个元素的地址。 *(x+i)
will get the value by dereferencing the address and &*(x+i)
will get the adress of the derefenced address. *(x+i)
将通过解引用地址获得值, &*(x+i)
将获得解引用地址的地址。 So the second statement is the same thing as just writing x+i
.所以第二个语句与只写x+i
是一样的。
However the explained line will probably give you a compiler error since it should more look like this: (&x[i]) == (&*(x+i)) && (&x[i]) == (x+i);
然而,解释的行可能会给你一个编译器错误,因为它应该更像这样: (&x[i]) == (&*(x+i)) && (&x[i]) == (x+i);
Conclusion: All these things do the same thing yet slightly differently.结论:所有这些事情都做同样的事情,但略有不同。
Lets suppose we have this piece of code让我们假设我们有这段代码
int i = 0;
int x[5]={1,2,3,4,5};
then this comparision is true:那么这个比较是正确的:
&x[i] == &*(x+i)
and this comparision is also true for similar reasons.出于类似的原因,这种比较也是正确的。
&*(x+i) == x+i;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.