- 论坛徽章:
- 0
|
原帖由 zx_wing 于 2009-5-18 09:07 发表 ![]()
呵呵,data[0]也和前面的紧邻的
如果仅仅是malloc(sizeof(packet)),则data[1]情况变为:
head (4 bytes) size (4 bytes) reply (1 byte) data[1] (1 bytes) padding (2 bytes)
如果是data[0]:
head (4 ...
谁说内存内存布局不一样了,只是改成data[1]啥的就可以正确求的offset(data,packet)的值了。
gcc的data[0]的实现就比较诡异了,实际应用中用这个东西是为了应付变长结构,这个时候使用sizeof(packet)是不适宜的,因为它考虑了结构末尾的padding。
我本来说了C99里面的data[]满足你的要求。
C99:
16 As a special case, the last element of a structure with more than one named member may
have an incomplete array type; this is called a flexible array member. With two
exceptions, the flexible array member is ignored. First, the size of the structure shall be
equal to the offset of the last element of an otherwise identical structure that replaces the
flexible array member with an array of unspecified length.106) Second, when a . (or ->)
operator has a left operand that is (a pointer to) a structure with a flexible array member
and the right operand names that member, it behaves as if that member were replaced
with the longest array (with the same element type) that would not make the structure
larger than the object being accessed; the offset of the array shall remain that of the
flexible array member, even if this would differ from that of the replacement array. If this
array would have no elements, it behaves as if it had one element but the behavior is
undefined if any attempt is made to access that element or to generate a pointer one past
it.
17 EXAMPLE Assuming that all array members are aligned the same, after the declarations:
struct s { int n; double d[]; };
struct ss { int n; double d[1]; };
the three expressions:
sizeof (struct s)
offsetof(struct s, d)
offsetof(struct ss, d)
have the same value. The structure struct s has a flexible array member d.
PS:如果你不和俺抬杠,俺也可以心平气和的和你谈。 |
|