*(&arr + 1) - arr 如何给出数组 arr 元素的长度? [英] How does *(&arr + 1) - arr give the length in elements of array arr?

查看:31
本文介绍了*(&arr + 1) - arr 如何给出数组 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 an int[5]
  • + 1 steps the pointer one int[5]
  • *(&arr + 1) dereferences the result back to an int(&)[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 two int[5]'s have decayed to int pointers, returning the diff between the two int pointers, which is 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

我会留下这个问题,它是 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.

这篇关于*(&amp;arr + 1) - arr 如何给出数组 arr 元素的长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆