指针越过对象末尾意味着什么? [英] what is pointer past the end of an object means?

查看:63
本文介绍了指针越过对象末尾意味着什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++ Primer第2章变量和基本类型"中,它表示:

In C++ Primer, Chapter 2, "Variables and Basic Types", it says:

指向一个对象的指针和一个指向不同对象末尾的指针可以保留相同的地址.

it is possible for a pointer to an object and a pointer one past the end of a different object to hold the same address.

我不是母语人士,所以这就是为什么我对句子对象末尾一个指针"感到困惑的原因.有人能告诉我这是什么意思吗?

I'm not a native speaker, and I think that's why I'm a bit confused by the sentence "a pointer one past the end of an object". Would anyone one tell me what it means please?

推荐答案

这意味着在

int a[] = { 1, 2 };
float b;

(void *)& a [2] ==(void *)& b 可能会比较正确.

& a [2] (或等价地, a + 2 )是刚好在 a 末尾的指针,因为数组仅包含索引为0和1的元素.

&a[2] (or equivalently, a+2) is a pointer just past the end of a, because the array only contains elements with indices 0 and 1.

通常,超出范围的数组索引是完全无效的(不允许访问 a [2] ,甚至不计算& a [3] ),但是有一个特殊的例外情况,用于计算数组末尾的地址,因为事实证明,这是非常有用的,例如,在遍历数组时,您需要一个结束值来知道何时停止循环

Normally, out-of-range array indices are completely invalid (accessing a[2] is not allowed, nor is even computing &a[3]), but there is a special exception for computing the address just past the end of an array, because as it turned out, that is quite useful, for example when iterating over an array and you need an end value to know when to stop the loop.

这篇关于指针越过对象末尾意味着什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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