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

查看:246
本文介绍了*(& 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天全站免登陆