ptr [i]和*(ptr + i)有什么区别? [英] What's the difference between ptr[i] and *(ptr + i)?

查看:489
本文介绍了ptr [i]和*(ptr + i)有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用指向数组的指针时,我总是通过使用索引器(例如myPtr[i] = stuff)来访问元素.但是,我最近正在查看

When using a pointer to an array, I've always accessed the elements by using an indexer, such as, myPtr[i] = stuff; however, I was recently looking over BitConverter's implementation and discovered that elements were accessed by doing, *(myPtr + i) = stuff.

我认为这很奇怪,因为两种方法(据我所知)都执行完全相同的操作,也就是说,它们返回myPtr + i的地址,但(在我看来)索引器方法看起来更具可读性

Which I thought was quite odd, since both methods (from what I know) do the exact same thing, that is, they return the address of myPtr + i, except (in my opinion) the indexer method looks much more readable.

那么Microsoft为什么选择以这种方式增加指针,这两种方法有什么区别(在性能上有好处)吗?

So why did Microsoft choose to increment pointers the way they did, what's the difference between the two methods (are there performance benefits)?

推荐答案

正如您所说,它们做同样的事情.

As you stated, they do the same thing.

实际上,当访问int*时,ptr[i]*(ptr + i)语法都将跳过边界检查,并且如果i大于数组长度,则指向数组边界之外的某些内存.

In fact, when accessing an int*, both ptr[i] and *(ptr + i) syntaxes will skip the bounds check, and point to some memory outside the array bounds if i is greater than the array length.

我很确定C#和C ++都使用C的*(ptr + index)语法继承了对数组指针的索引访问.我很确定这是两种语法都可用的唯一原因.

I'm pretty sure C#, as well as C++, inherited the indexed access to an array pointer using the *(ptr + index) syntax from C. I'm pretty sure that's the only reason why both syntaxes are available.

这篇关于ptr [i]和*(ptr + i)有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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