是否指针算法仍然阵列以外的地方工作? [英] Does pointer arithmetic still work outside the array?

查看:102
本文介绍了是否指针算法仍然阵列以外的地方工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读的指针运算都是,只要你不离开数组的边界定义。我不知道我完全理解这是什么意思,我是有点担心。因此这个问题。

I am always reading that pointer arithmetic is defined as long as you don't leave the bounds of the array. I am not sure I completely understand what this means and I was a little worried. Hence this question.

假设我开始与指针数组的开头:

Suppose I start with a pointer to the beginning of an array:

int *p = (int*) malloc(4 * sizeof(int));

现在我创建了位于数组范围之外的两个新指针:

Now I create two new pointers that lie outside the bounds of the array:

int *q = p + 10;
int *r = p - 2;

现在指针 Q-10 Q-9 ... R + 2 R + 3 ,等所有的谎言数组的边界内。他们是有效的?例如,为研究[3] 保证以产生相同的结果为 P [1]

Now the pointers q-10, q-9, ..., r+2, r+3, and so on all lie inside the bounds of the array. Are they valid? For example, is r[3] guaranteed to give the same result as p[1]?

我已经做了一些测试,它的作品。但我想知道这是通常的C规格覆盖。具体来说,我使用Visual Studio 2010,Windows和我编程在本地C(不是C ++)。我有没有佣金?

I have done some testing and it works. But I want to know if this is covered by the usual C specifications. Specifically, I am using Visual Studio 2010, Windows, and I am programming in native C (not C++). Am I covered?

推荐答案

你在你使用的执行情况,以及最流行的实现做什么工作,但它不符合C.克里斯引用,

What you're doing works on the implementation you're using, as well as most popular implementations, but it's not conforming C. As chris cited,

§6.5.6/ 8:如果指针操作数和结果指向相同的数组对象,或者一个过去的数组对象的最后一个元素的元素两者的评估也不得产生溢出;否则,这种行为是未定义

§6.5.6/8: If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined

这是不确定的,这一事实可能会成为未来越来越重要,更先进的静态分析让编译器把这种code到致命错误,而不会产生运行成本。

The fact that it's undefined will probably become increasingly important in the future, with more advanced static analysis allowing compilers to turn this kind of code into fatal errors without incurring runtime cost.

顺便说一句,对于被不确定的指针减去未在同一阵列中的历史原因是分段存储器(想想16位x86;那些熟悉它要考虑的大而全的内存模型)。虽然指针可能涉及段和偏移分量,编译器可以做的正好抵消部分算术,以避免运行时的成本。这使得指针之间的算术不在同一网段,因为不同的是失去了高部分无效。

By the way, the historical reason for subtracting pointers not within the same array being undefined is segmented memory (think 16-bit x86; those familiar with it will want to think of the "large" memory model). While pointers might involve a segment and offset component, a compiler could do the arithmetic just on the offset component to avoid runtime cost. This makes arithmetic between pointers not in the same segment invalid since the "high part" of the difference is lost.

这篇关于是否指针算法仍然阵列以外的地方工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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