问题描述
请您就此代码的可移植性发表意见吗?
/ * --------开始findindex.c -------- * /
struct Foo {int junk0; };
struct Bar {int junk1; struct Foo foo; int junk2; };
int findindex(struct Bar * bars,struct Foo * fooptr)
/ *上一页:
*条点数到(第一个元素)一个Bar数组。
* fooptr指向一个条形元素的''foo''成员,
*即fooptr == &安培; bars [i] .foo for some valid index i
*返回:
* i的实际值,如上所定义。
* /
{
return((char *)fooptr - (char *)& bars [0] .foo)/ sizeof * bars;
}
/ * --------结束findindex.c -------- * /
Ike
Could you please give your opinion on the portability of this code?
/* -------- begin findindex.c -------- */
struct Foo { int junk0; };
struct Bar { int junk1; struct Foo foo; int junk2; };
int findindex(struct Bar * bars, struct Foo * fooptr)
/* Pre:
* bars points to (the first element of) an array of Bar.
* fooptr points to the ''foo'' member of an element of bars,
* i.e. fooptr == & bars[i].foo for some valid index i
* Returns:
* the actual value of i, as defined above.
*/
{
return ((char*)fooptr - (char*)&bars[0].foo) / sizeof *bars;
}
/* -------- end findindex.c -------- */
Ike
推荐答案
对我来说没问题(只要参数是你告诉的)。一个原来的
本地人将是
return(struct Bar *)((char *)fooptr - offset_of(struct Bar,foo)) - bars;
避免(显式)除法。你是否考虑过返回
a size_t而不是int(结果不能为负数,或者你用无效的参数调用
)?
问候,Jens
-
\ Jens Thoms Toerring ___
\ __________________________
Ow,''令人费解的。 AFAICT,它不是严格的便携式,但你会很难找到一个无法工作的实施方案。它将需要实施者的故意。
Richard
Ow, that''s convoluted. AFAICT, it''s not strictly portable, but you''d be
hard put to find an implementation where it wouldn''t work. It would
require willful perversity of the implementor.
Richard
对我来说没问题(只要参数是你所说的)。一个alter-
本机将返回(struct Bar *)((char *)fooptr - offset_of(struct Bar,foo)) - 吧;
这避免了(显式)除法。
Looks ok to me (as long as the arguments are what you tell). An alter-
native would be
return (struct Bar*)((char*)fooptr - offset_of(struct Bar, foo)) - bars;
which avoids the (explicit) division.
值得注意的是,后者的sizeof * bars的隐式除法
形式可能比显式优化更好。
对于指针减法中的隐式除法,编译器知道
除法的结果必须确切地说,它允许强度降低
将其转换为简单的模乘。类似的强度降低
可能用于潜在的非精确划分,但它们更复杂。
-
Kevin Bracey,首席软件工程师
Tematic Ltd电话:+44(0)1223 503464
182-190 Newmarket Road传真:+44(0 )1728 727430
剑桥,CB5 8HE,英国WWW:
这篇关于找到索引,给定指向成员的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!