限制指针算术或比较的原理是什么? [英] What is the rationale for limitations on pointer arithmetic or comparison?

查看:53
本文介绍了限制指针算术或比较的原理是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C/C ++中,仅定义指针上的加法或减法如果结果指针位于原始指向的完整对象内.而且,仅当两个指针对象是两个指针时,才能执行两个指针的比较. 完整对象的唯一子对象.

In C/C++, addition or subtraction on pointer is defined only if the resulting pointer lies within the original pointed complete object. Moreover, comparison of two pointers can only be performed if the two pointed objects are subobjects of a unique complete object.

出现此类限制的原因是什么?

What are the reasons of such limitations?

我认为是分段内存模型(请参见此处§ 1.2.1)可能是原因之一,但由于编译器实际上可以在所有指针上定义总顺序,如 answer ,我对此表示怀疑.

I supposed that segmented memory model (see here §1.2.1) could be one of the reasons but since compilers can actually define a total order on all pointers as demonstrated by this answer, I am doubting this.

推荐答案

在某些体系结构中,程序空间和数据空间是分开的,只是不可能减去两个任意指针.指向函数或const静态数据的指针将与普通变量位于完全不同的地址空间中.

There are architectures where program and data spaces are separated, and it's simply impossible to subtract two arbitrary pointers. A pointer to a function or to const static data will be in a completely different address space than a normal variable.

即使您随意在不同的地址空间之间提供了排名,diff_t类型也可能需要更大的大小.比较或减去两个指针的过程将非常复杂.对于设计用于速度的语言来说,这是个坏主意.

Even if you arbitrarily supplied a ranking between different address spaces, there's a possibility that the diff_t type would need to be a larger size. And the process of comparing or subtracting two pointers would be greatly complicated. That's a bad idea in a language that is designed for speed.

这篇关于限制指针算术或比较的原理是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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