*(&arr + 1) - arr 如何给出数组大小 [英] How *(&arr + 1) - arr is working to give the array size

查看:40
本文介绍了*(&arr + 1) - arr 如何给出数组大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int arr[] = { 3, 5, 9, 2, 8, 10, 11 };      
int arrSize = *(&arr + 1) - arr;
std::cout << arrSize;

我不知道这是如何工作的.所以任何人都可以帮我解决这个问题.

I am not able to get how this is working. So anyone can help me with this.

推荐答案

如果我们绘制"数组和指针一起,它看起来像这样:

If we "draw" the array together with the pointers, it will look something like this:

+--------+--------+-----+--------+-----+
| arr[0] | arr[1] | ... | arr[6] | ... |
+--------+--------+-----+--------+-----+
^        ^                       ^
|        |                       |
&arr[0]  &arr[1]                 |
|                                |
&arr                             &arr + 1

表达式&arr&arr + 1 的类型是int (*)[7].如果我们取消引用这些指针中的任何一个,我们会得到一个 int[7] 类型的值,并且与所有数组一样,它将衰减为指向其第一个元素的指针.

The type of the expressions &arr and &arr + 1 is int (*)[7]. If we dereference either of those pointers, we get a value of type int[7], and as with all arrays, it will decay to a pointer to its first element.

所以发生的事情是我们取了指向 &arr + 1 的第一个元素的指针之间的差异(取消引用确实使这个 UB,但仍然可以与任何正常的编译器一起使用)和指向 &arr 的第一个元素的指针.

So what's happening is that we take the difference between a pointer to the first element of &arr + 1 (the dereference really makes this UB, but will still work with any sane compiler) and a pointer to the first element of &arr.

所有的指针运算都是在被指向类型的基本单元中完成的,在这种情况下是int,所以结果是int元素的数量指向的两个地址之间.

All pointer arithmetic is done in the base-unit of the pointed-to type, which in this case is int, so the result is the number of int elements between the two addresses being pointed at.

知道数组会自然地衰减到指向其第一个元素的指针可能很有用,即表达式 arr 将衰减到 &arr[0], 类型为 int *.

It might be useful to know that an array will naturally decay to a pointer to its first element, ie the expression arr will decay to &arr[0], which will have the type int *.

另外,对于任何指针(或数组)p和索引i,表达式*(p + i)完全等于p[i].所以 *(&arr + 1) 实际上与 (&arr)[1] 相同(这使得 UB 更加明显).

Also, for any pointer (or array) p and index i, the expression *(p + i) is exactly equal to p[i]. So *(&arr + 1) is really the same as (&arr)[1] (which makes the UB much more visible).

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

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