开发者

Purpose of dereferencing a pointer as a parameter in C

I recently came along this line of code:

CustomData_em_free_block(&em->vdata, &eve->data);

And I thought, isn't:

a->b

just syntactic sugar for:

(*a).b

With that in mind, this line could be re-written as:

CustomData_em_free_block(&(*em).v开发者_如何学Cdata, &(*eve).data);

If that's the case, what is the point of passing in

&(*a), as a parameter, and not just a? It seems like the pointer equivalent of -(-a) is being passed in in, is there any logic for this?

Thank you.


This:

&(*em).vdata

is not the same as this:

em.vdata

It is the same as this:

&((*em).vdata)

The ampersand takes the address of vdata, which is a member of the struct pointed to by em. The . operator has higher precedence than the & operator.


Here's what you're missing: &em->vdata is the same as &(em->vdata), not (&em)->vdata. That is, it's the address of the vdata member of the structure pointed to by em. This should be clear if you look at the type of em - it's a pointer.

Yes, you can always rewrite a_ptr->member as (*a_ptr).member, but why bother? That's the point of the syntactic sugar.


"If that's the case, what is the point of passing in &(*a), as a parameter, and not just a?"

Usually none. But notice that your sample code doesn't compare &(*a) and a. Your sample code compares &(*a) and b, where b is offset from a by whatever the distance is from the start of em to em's vdata member.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜