How to use a macro to find the memory offset address of a struct

Source: Internet
Author: User

#define OFFSET (Type,field) ((size_t) & (((type*) 0)->field)

In C, the ANSI C standard allows a constant with a value of 0 to be cast to a pointer of any type, and the result is a null pointer, a null pointer, so the result of a 0 pointer operation ((type*) 0) is a null pointer of type type*. However, it is of course illegal to use this null pointer to access the type's members.

Because the intent of & (((type*) 0)->field is simply to calculate the address of the field, the C compiler does not generate code to access the type member at all, but simply calculates the constant address at compile time based on the content layout and struct instance address of type. This completely avoids possible problems with accessing memory through a null pointer. And because the struct address is 0, the value of the field address is the offset of the field relative to the base address of the struct.

Examples of the program are:

#include <stdio.h> #define OFFSET (Type,field) ((size_t) & (((type*) 0)->field)) struct Mystr{char A;short b; Double c;int D;}; int main () {printf ("%d\n", offset (struct mystr,a));p rintf ("%d\n", offset (struct mystr,b));p rintf ("%d\n", offset ( struct mystr,c));p rintf ("%d\n", OffSet (struct mystr,d)); return 0;}
The program runs as (32-bit machine, Char takes one byte, short is two bytes, double takes 8 bytes, int is 4 bytes):

0

2

8

16

Results Analysis:

The above method avoids instantiating a type object, and the evaluation is performed during compilation, with no run-time burden, and the program efficiency is greatly improved.

How to use a macro to find the memory offset address of a struct

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.