如何指针增量工作? [英] How does pointer incrementation work?

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

问题描述

我们有一个数组: INT P [100] 。结果
为什么 P [I] 等同于 *(P + I),而不是 *( p + I *的sizeof(INT))


解决方案

  

为什么ρ[i]为相当于*(P + I),而不是*(P + I *的sizeof(int)的)?


由于一些处理器架构无法提领,不指向由其类型的大小对齐的地址的指针。该basicly意味着一个指针
   4字节整数应始终指向一个ADRESS是4的倍数。

当某个程序试图取消引用指针错位可能会引起一个总线错误。你可以阅读更多关于它在这里 href=\"https://en.wikipedia.org/wiki/Bus_error\" rel=\"nofollow\">。

你所要求的是, P + 1 应当由一个字节,而不是一个元素递增指针。如果语言的目的是这样写点++ 将不再适用于其他类型的指针不是字符。这也将导致与指针对齐大问题,当一个程序员忘记写 * sizeof的(* P)来使加法。

这可能是混乱的,但也有为什么语言的目的是通过这种方式非常有效的原因。

We have an array: int p[100].
Why p[i] is equivalent to *(p+i) and not *(p+i*sizeof(int)) ?

解决方案

Why p[i] is equivalent to *(p+i) and not *(p+i*sizeof(int)) ?

Because some processor architectures cannot dereference a pointer that does not point to an address that is aligned by the size of its type. That basicly means that a pointer to a 4 byte integer should always point to an adress that is the multiple of 4.

When a program tries to dereference a misaligned pointer it might cause a "Bus error". You can read more about it here on Wikipedia.

What you are asking for is that p + 1 should increment the pointer by one byte instead of one element. If the language was designed that way writing p++ would no longer be valid for pointers of other types than char. It would also cause big problems with pointer alignment when a programmer forgets to write * sizeof(*p) to make the addition.

It might be confusing but there are very valid reasons for why the language was designed this way.

这篇关于如何指针增量工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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