Array of structures and pointer arithmetic

回眸只為那壹抹淺笑 提交于 2019-12-11 01:19:58

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!