Google
  Web www.spinics.net

Re: A tough C construct in Linux Kernel's implementation

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]


>
> #define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
>
> is returning the "Offset of a Memeber inside a struct/class Type". I
> didn't logically understand how is that happenning...:-(
>
> I expect the outcome of &((TYPE *)0)->MEMBER to be the address of the
> member 'MEMBER' of type 'TYPE'. Now, how does that address becomes
> offset has totally gone out of my understanding...
>

You are right ... &((TYPE *)0)->MEMBER is the address of member
"MEMBER" of type "TYPE". But consider that the (base) address of the
structure of type "TYPE" is NULL (0) as shown in above expression, and
hence the address of "MEMBER" is nothing but the offset.

An example:

Say you have:

struct student {
  int roll no;
  int age;
}

if you write offsetof(student, age), it converts to:

((size_t) &((student *)0)->age)

= ((size_t) &((student*)NULL)->age)

= ((size_t) 4 )    (Considering int = 4 bytes)

=4 = offset

Regards,

Rajat
-
To unsubscribe from this list: send the line "unsubscribe linux-newbie" in
the body of a message to majordomo@xxxxxxxxxxxxxxx
More majordomo info at  http://vger.kernel.org/majordomo-info.html
Please read the FAQ at http://www.linux-learn.org/faqs

[Site Home]     [Audio]     [Hams]     [Kernel Newbies]     [Memory]     [Security]     [Netfilter]     [Bugtraq]     [Writing Drivers]     [Photo]     [Yosemite Photos]     [Yosemite News]     [MIPS Linux]     [ARM Linux]     [Linux Security]     [Linux RAID]     [Samba]     [Video 4 Linux]     [Linux Resources]     [Fedora Users]

  Powered by Linux