Question about accessing array element pointers

I have an array allocated like this
typedef unsigned char Byte;
Byte *MyArray = (Byte*)malloc(10);

Now I want to find the address of the 5th element (index 4) in the array. So do I do this:
ElementAddr = &MyArray[4]

Or do I do this:
ElementAddr = &(MyArray[4])

Note the parentheses around the thing which I'm trying to get the address for. Are these parentheses needed? I did that because it's an array, and I want to make sure that it knows I'm trying to get the address for the array cell at index 4, not get the base address of the array and then add 4 to it (though these would be the same with Byte sized arrays, it wouldn't be the same for arrays with larger data types). However, would it exhibit this undesired behavior if I left off the parentheses? I hope somebody knows. I'm trying to make my code as small as possible, and it would be nice to remove extra parentheses if possible.
Last edited on
Use:
ElementAddr = MyArray + 4;


Bottom of http://www.cplusplus.com/doc/tutorial/operators/
has operator precedence table.

The subscript operator [] is has higher precedence than the reference operator &.
1
2
3
4
5
6
&MyArray[4]
// is same as
&(MyArray[4])

// and different than
(&MyArray)[4]


The subscript operator and pointer math do the same:
1
2
3
MyArray[4]
// is same as
*(MyArray+4)

You don't need value from address MyArray+4 and thus there is no need to dereference.

Thus the:
ElementAddr = MyArray + 4;
Topic archived. No new replies allowed.