[Ilugc] C doubt involving pointers

  • From: binand@xxxxxxxxx (Binand Sethumadhavan)
  • Date: Wed May 18 12:57:04 2005

On 18/05/05, Mohammed Riyaz <p_mdriyaz@xxxxxxxxxxx> wrote:

Hi,
I came across this question in C faq's.
Could some one explain the #define statement specified below.

2.14:   How can I determine the byte offset of a field within a
        structure?

                #define offsetof(type, mem) ((size_t) \
                        ((char *)&((type *)0)->mem - (char *)(type *)0))

This takes the address of the field within the structure, and
subtracts the address of the structure itself. The difference is
assumed to be the offset of the field within the structure.

1                      2                    3                     4
|----------------------|--------------------|---------------------|
start of struct/        start of field2      start of field3       end
start of field1

(view in a fixed-width font please)

If you need the offset (in bytes) of say field3, then you can see from
the figure that it is the address of (3) - the address of (1).

Binand

Other related posts: