2

How are arrays of structures accessed using pointer arithmetic?

suppose I have a struct

struct point{
int x;
int y;
}collection[100];

Suppose I have a function

int func(struct point *collection,int size)   

Inside this function I access the element as shown below.

collection[0].x 

Is this the same as *(collection + 0).x? Since the . operator has higher precedence than the * operator, first the collection pointer is incremented by 0, and the the dot operator is applied, and then the pointer dereferenced? Somehow this does not make sense; any clarification is appreciated.

3
  • 1
    If you really want to bake your noodle, can you work out what 0[collection].x is? Commented Feb 4, 2014 at 7:13
  • @Eric Lippert (*(0 + collection)).x, from what I gathered the [] operator means...a[5] = *(a+5) so 5[a] means *(5+a) therefore 0[collection].x is the same as collection[0].x took me some time, did I get it right. Commented Feb 11, 2014 at 13:54
  • You got it! Indexing is just a fancy kind of addition, and addition is commutative. Commented Feb 11, 2014 at 14:50

1 Answer 1

2

Is this the same as *(collection + 0).x?

No. Your explanation is absolutely correct, . has higher precedence than *, so that second expression is parsed as *((collection + 0).x). collection[i].x on the other hand is equivalent to (*(collection + i)).x.

Actually this awkwardness is the reason the -> operator was introduced, so assuming y is some non-trivial expression, you can write

y->x

instead of

(*(y)).x

Although obviously collection[0].x is much cleaner than (collection + 0)->x in this particular instance.

Sign up to request clarification or add additional context in comments.

2 Comments

(*(collection + i)).x, this makes much more sense now, so arrays of structures has an extra set of parenthesis before the dot operator when using pointer arithmetic.
@tesseract: Well I guess the essence is that if you have a pointer to the struct (for example collection + i, which is a pointer), and you want to access a field of the struct pointed to by your pointer, you need to dereference the pointer and then apply the dot operator to it. Since the dot operator has quite high precedence, you need to force the dereference using an explicit pair of brackets.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.