结构和指针运算阵列 [英] Array of structures and pointer arithmetic

查看:98
本文介绍了结构和指针运算阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是如何使用指针运算访问结构数组?

假设我有一个结构

 结构点{
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 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.

这篇关于结构和指针运算阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆