的C指针运算 [英] C pointer arithmetic

查看:122
本文介绍了的C指针运算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有鉴于此code:

int *p, *q;

p = (int *) 1000;
q = (int *) 2000;

什么是① - P 如何

推荐答案

它实际上是不确定的,根据标准。指针运算是不能保证工作,除非指针都指向无论是在一个元素,或者只是超越,在同一个阵列。

It's actually undefined, according to the standard. Pointer arithmetic is not guaranteed to work unless the pointers are both pointing to either an element in, or just beyond, the same array.

该标准的相关部分6.5.6:9(C1X的n1362草案,但这个自C99并没有改变),其中规定:

The relevant section of the standard is 6.5.6:9 (n1362 draft of c1x but this hasn't changed since c99) which states:

当两个指针相减,两个人都要指向同一数组对象的元素,
  或者一个过去的数组对象的最后一个元素;结果是该差
  两个数组元素的下标。

When two pointers are subtracted, both shall point to elements of the same array object, or one past the last element of the array object; the result is the difference of the subscripts of the two array elements.

您将最有可能获得250如果你的 INT 的数据类型为4个字节,但不能保证。未定义行为(不同实现定义的行为)意味着只是,不确定的。任何事情都有可能发生,最多的,包括很大比例的时空彻底毁灭。

You'll most likely get 250 if your int datatype is 4 bytes but there's no guarantee. Undefined behaviour (unlike implementation-defined behaviour) means just that, undefined. Anything can happen, up to an including the total destruction of a large proportion of space-time.

一个进修班:


  • 定义的行为是什么,是由标准规定。实现必须这样做是符合的。

  • 实现定义的行为是留给实现,但它必须清楚地记录该行为。使用这个,如果你不关心可移植性太多了。

  • 未定义行为意味着什么事情都有可能发生。永远不要做!

这篇关于的C指针运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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