问题
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.
回答1:
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.
来源:https://stackoverflow.com/questions/21544177/array-of-structures-and-pointer-arithmetic