*(&arr + 1) - arr 如何给出数组 arr 元素的长度? [英] How does *(&arr + 1) - arr give the length in elements of array arr?
问题描述
#include <iostream>
using namespace std;
int main() {
int arr[5] = {5, 8, 1, 3, 6};
int len = *(&arr + 1) - arr;
cout << "The length of the array is: " << len;
return 0;
}
对于上面的代码,我不太明白这两段代码是做什么的:
For the code above, I don't quite understand what these two pieces of codes are doing:
*(&arr + 1)
和
*(&arr)
&arr
谁能解释一下?因为当我运行以下两个代码时,我得到以下相同的输出:
Could someone explains? Because when I run the following two codes, I get the same output for the following:
&arr
(我觉得这个指向arr的第一个元素的地址)
&arr
(I think this point to the address of the first element of arr)
*(&arr)
然后我不太明白这是做什么的,符号 *
对 &arr
(即到这里的地址)?,因为我运行它们时两个输出是相同的
*(&arr)
then I don't quite understand what this do, what does the symbol *
do to &arr
(i.e. to the address here)?, because the two outputs are the same when I run them
最后,当一个整数说 1 被这里的代码添加到地址时,到底发生了什么:&arr + 1
and finally what is it exactly happening when an integer say 1 is added to the address by this code here:
&arr + 1
推荐答案
这是一个雷区,但我会试一试:
This is a mine field, but I'll give it a try:
&arr
返回一个指向int[5]
的指针+ 1
指针步进一int[5]
*(&arr + 1)
将结果解引用回int(&)[5]
我不知道这是否会导致未定义的行为,但如果不会,下一步将是:*(&arr + 1) - arr
在两个int[5]
衰减为int
后进行指针运算指针,返回两个int
指针之间的差异,即5
.
&arr
returns a pointer to anint[5]
+ 1
steps the pointer oneint[5]
*(&arr + 1)
dereferences the result back to anint(&)[5]
I don't know if this causes undefined behavior, but if it doesn't, the next step will be:*(&arr + 1) - arr
does pointer arithmetics after the twoint[5]
's have decayed toint
pointers, returning the diff between the twoint
pointers, which is5
.
重写以使其更清晰:
int arr[5] = {5, 8, 1, 3, 6};
int (*begin_ptr)[5] = &arr + 0; // begin_ptr is a int(*)[5]
int (*end_ptr)[5] = &arr + 1; // end_ptr is a int(*)[5]
// Note:
// begin_ptr + 1 == end_ptr
// end_ptr - begin_ptr == 1
int (&begin_ref)[5] = *begin_ptr; // begin_ref is a int(&)[5]
int (&end_ref)[5] = *end_ptr; // end_ref is a int(&)[5] UB here?
auto len = end_ref - begin_ref; // the array references decay into int*
std::cout << "The length of the array is: " << len << '\n'; // 5
我会留下这个问题,它是 UB 还是未打开,但在分配引用的存储之前引用一个对象确实看起来有点可疑.
I'll leave the question if it's UB or not open but referencing an object before the referenced storage has been allocated does look a bit suspicious.
这篇关于*(&arr + 1) - arr 如何给出数组 arr 元素的长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!