Common methods of obtaining the offset of structure field in ANSI C

Source: Internet
Author: User

from Http://blog.chinaunix.net/u2/62910/showart_492571.html

Suppose you define a struct type named MyStruct in an ANSI C program with a field named MyField, how do I get its offset in the struct?

typedef struct MYSTRUCT_TAG
{
//Some fields
...

Long MyField;

// other fields
...
} mystruct;


The easiest way to think about it should be similar to the following code:

size_t GetOffset ()
{
MyStruct s;

Return (size_t) ((char*) (&s.myfield)-(char*) (&s));
}

This code does accomplish the task, but in order to get the offset value, the function has to define a mystruct struct instance, but is this necessary? Think about when the structure's memory layout was decided by who? Yes, it is determined by the compiler at compile time, it will not change once it is determined, and the field offset dependent on the structure's in-memory layout will be determined and no longer changed. now that the compiler has an insight into the internals of the compiler, there is a good reason to ask it to provide this information to the program at compile time. How to do it? Take a look at the following code:

#define MY_OFFSET (size_t) & (((mystruct*) 0)->myfield)

The My_offset macro defined above is the offset of the myfield you want. How can the cast structure pointer be used to access the struct field? In fact, this expression does not have to access the MyField field at all. The ANSI C standard allows any constant with a value of 0 to be cast to a pointer of any one type , and the result of the conversion is a null pointer, so the result of ((mystruct*) 0) is a null pointer of type mystruct*. It is certainly illegal to use this null pointer to access the members of the MyStruct, but the intent of & (((mystruct*) 0)->myfield is not to access the contents of the MyField field, but only to calculate when the first address of the struct instance is ( mystruct*) 0) The address of the MyField field. the Smart compiler simply does not generate code to access MyField, but simply calculates this (constant) address at compile time based on MyStruct's memory layout and struct instance first, which completely avoids the problem of accessing memory through a null pointer. And because the value of the first address is 0, the value of this is the offset of the field relative to the base address of the struct.

The above approach avoids having to instantiate a MyStruct object, and the evaluation is performed at compile time, with no run-time burden. In fact, this method of using the compiler to master the information of the whole program to calculate certain values at compile time is similar to the popular (static) meta-programming techniques in C + + programming, except that C + + programmers can use template technology to complete very complex computations at compile time, while the lack of ANSI supported by the template c the capacity in this regard is much weaker.

Perhaps because the structure of the field offset is very common, ANSI C in the standard header file Stddef.h specifically defines a shape such as offsetof (S,M) macro to find any one of the structure type of the offset of a field, and the majority of C development system implementations have adopted the above method, for example:

VC7.1
#ifdef _win64
#define OFFSETOF (S,m) (size_t) ((ptrdiff_t) & ((((s) 0)->m))
#else
#define OFFSETOF (S,m) (size_t) & (((S *) 0)->m)
#endif


Lcc-win32, Last Updated:monday, 13-dec-2004 04:05:23 EST
#define OFFSETOF (s,m) (int) & (((s) 0)->m)


Borland C + + 5.5.1 for WIN32
#define OFFSETOF (S_name, M_name) (_size_t) & ((((s_name _far *) 0)->m_name)


MinGW 3.1.0 (GCC 3.2.3)
#ifndef __cplusplus
#define OFFSETOF (Type, MEMBER) ((size_t) & ((TYPE *) 0)->member)
#else/ * C + + *
/* The reference cast is necessary to thwart a operator& that might
Be applicable to Member´s type.  See Dr. 273 for details. */
#define OFFSETOF (TYPE, MEMBER) (reinterpret_cast <size_t>/
(&reinterpret_cast <char &> (static_cast <type *> (0)->member)))
#endif/ * C + + *

It can be seen that this concise and effective method has been accepted by C programmers as a customary method (idiom).

Common methods of obtaining the offset of structure field in ANSI C

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.