结构和指针运算阵列 [英] Array of structures and pointer arithmetic
问题描述
是如何使用指针运算访问结构数组?
假设我有一个结构
结构点{
INT X;
诠释Ÿ;
}收藏[100];
假设我有一个函数
INT FUNC(结构点*集合,INT大小)
在这个函数我访问元件,如下所示。
集合[0] .X
这是一样的 *(集合+ 0).X
?因为。
运营商具有较高的precedence比 *
运营商,先收集指针由0增加,和点运算应用,然后将指针取消引用?不知怎的,这是没有意义的;任何澄清是AP preciated。
这是一样的
*(集合+ 0).X
?
块引用>没有。你的解释是绝对正确的,
。
具有较高的precedence比*
,使第二前pression被解析为*((收集+ 0).X)
。集合[I] .X
,另一方面相当于(*(集合+ I))。X
。其实这尴尬的原因是在
- >
运营商推出,所以假设是
是一些非琐碎的前pression,你可以写Y-X的催化剂
而不是
(*(Y)),X
虽然明显
集合[0] .X
较干净多了(收集+ 0) - > X
在此特定实例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.解决方案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 assumingy
is some non-trivial expression, you can writey->x
instead of
(*(y)).x
Although obviously
collection[0].x
is much cleaner than(collection + 0)->x
in this particular instance.这篇关于结构和指针运算阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!