#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;
}
Run Code Online (Sandbox Code Playgroud)
对于上面的代码,我不太明白这两段代码是做什么的:
*(&arr + 1)
Run Code Online (Sandbox Code Playgroud)
和
*(&arr)
&arr
Run Code Online (Sandbox Code Playgroud)
有人可以解释一下吗?因为当我运行以下两个代码时,我得到以下相同的输出:
&arr (我认为这指向arr的第一个元素的地址)
*(&arr)那么我不太明白这是做什么的,符号*对&arr(即这里的地址)有什么作用?,因为当我运行它们时,两个输出是相同的
最后,当一个整数说 1 被这里的代码添加到地址时,到底发生了什么:
&arr + 1
这是一个雷区,但我会尝试一下:
&arr返回一个指向int[5]+ 1将指针移一int[5]*(&arr + 1)将结果取消引用回int(&)[5]*(&arr + 1) - arrint[5]在两个衰减为指针后进行指针算术int,返回两个指针之间的差异int,即5。重写以使其更清晰一些:
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
Run Code Online (Sandbox Code Playgroud)
我会留下这个问题,如果它是 UB 或未打开,但在分配引用的存储之前引用一个对象确实看起来有点可疑。