Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between ptr[i] and *(ptr + i)?

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.

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.

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

like image 681
Sam Avatar asked Jun 16 '14 10:06

Sam


2 Answers

As you stated, they do the same thing.

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.

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.

like image 142
dcastro Avatar answered Sep 28 '22 09:09

dcastro


From CSharp Language Specification (18.5.3):

A pointer element access of the form P[E] is evaluated exactly as *(P + E). (...) The pointer element access operator does not check for out-of-bounds errors and the behavior when accessing an out-of-bounds element is undefined. This is the same as C and C++.

There are no differences.

like image 25
gwiazdorrr Avatar answered Sep 28 '22 10:09

gwiazdorrr