Re: offsetof



On 30 Sep 2005 05:04:10 -0700, junky_fellow@xxxxxxxxxxx wrote:

>
>Flash Gordon wrote:
>> junky_fellow@xxxxxxxxxxx wrote:
>> > luke wrote:
>
>Thanx Flash for the nice explanation. I have few more questions to ask.
>1) K&R A.7.7
> If two pointers to objects of the same type are subtracted
> the result is a signed integral value
> representing the displacement between the pointed-to objects.
> The value is undefined unless the pointers point to objects within
>the
> same array.
> In the offsetof macro, is the substraction defined ?

No it's undefined behaviour. Undefined by the C standard that is.
Which means that an implementation can do what it likes. In this case,
the particular library involved knows what the implementation will do
with the expression. This doesn't give the user of the library a
license to do pointer subtractions like this.


>
>2) If this is defined then the macro,
>#define offsetof(type, mem) ((size_t) \
> ((char *)&((type *)0)->mem - (char *)(type *)0))
>
>should work on all implementations ? So, why should we use
>implementation
>specific offsetof macro ?

Because conversion of integer to pointer and vice versa is
implementation defined and as you pointed out, the subtraction is UB.

darkknight
.



Relevant Pages

  • Re: Help
    ... Flash Gordon wrote: ... group,I am searching for an IT job and this sunday I have an ... Interview. ... Remember that arrays and pointers are fundamentally different ...
    (comp.lang.c)
  • Re: a pointer that points to itself
    ... Flash Gordon wrote: ... > Nils O. Selåsdal wrote: ... >> tedu wrote: ... > types and pointers to pointers. ...
    (comp.lang.c)
  • Re: a pointer that points to itself
    ... pete wrote: ... > Flash Gordon wrote: ... >> Actually, if you pick the correct types, you don't have a problem with ... >> types and pointers to pointers. ...
    (comp.lang.c)
  • Re: a pointer that points to itself
    ... types and pointers to pointers. ... Flash Gordon ... Living in interesting times. ... Although my email address says spam, it is real and I read it. ...
    (comp.lang.c)
  • Re: offsetof
    ... Not just your reading the FAQ, ... this is why offsetof macro is implementation specific. ... > If you looks in the system headers for your implementation you ... If two pointers to objects of the same type are subtracted ...
    (comp.lang.c)