C++: &a[2] - &a[1] ==?
a
is array of integers, if I try to subtract the address value of &a[2] - &a[1] == ?
what should the result be 4 or 1 ?
EDIT: see 4th comment on top answer here why he says 1 ?? this is why I'm confused I thought it will be 4
EDIT: here is a test
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
&a[2]
与&(*(a + 2))
相同(即(a + 2)
)和 < code>&a[1] 与&(*(a + 1))
相同(即(a + 1)
)。所以答案是 1。&a[2]
is same as&(*(a + 2))
(i.e(a + 2)
) and&a[1]
is same as&(*(a + 1))
(i.e.(a + 1)
). So answer will be 1.指针减法给出的是元素的差异,而不是字节。无论数组的元素类型是什么,
&a[2] - &a[1]
的结果始终为 1,因为它们相距 1 个元素。Pointer subtraction gives you the difference in elements, not bytes. It does not matter what the element type of the array is, the result of
&a[2] - &a[1]
will always be 1, because they are 1 element apart.它始终为 1。指针算术不关心每个元素具有的字节数,这非常有用。比较一下:
当您使用数组时,您通常对元素感兴趣,而不是对组成它们的字节感兴趣,这就是为什么C中的指针算术是这样定义的。
It is always 1. The pointer arithmetics are not concerned with the number of bytes that each element has, and this is very useful. Compare these:
When you work with arrays you are usually interested in the elements, not in the bytes comprising them, and that is why pointer arithmetics in C has been defined this way.
差异必须为 1。当您比较指针时,您总是会得到元素的差异。
The difference must be 1. When you compare pointers you will always get the difference of elements.
由于这是 C++,我假设您没有重写
a
类型上的&
或*
运算符。考虑到这一点,以下情况是正确的:Since this is C++, I'm going to assume that you have not overridden the
&
or*
operators on whatever typea
is. Minding that, the following is true:这里的几个答案(自发布该答案后已删除)显然考虑了 byte*:
输出是:
两个地址,但根据存储地址的变量的声明,两者之间的差异可以是 1 或 4 。
A couple of the answers here (deleted since this answer was posted) clearly had byte* in mind:
output is:
Two addresses but depending on the declaration of the variable the addresses are stored in, the difference between the two can be 1 or 4.