C offsetof- body member offset value computing structure

1. Role:

The body member of the offset value calculated structure


2. Use the scene:

Node type structures in the body may be defined in the data structure, corresponding to the embedded data structures


3. Examples of (embedded list data structure):

Example code:

#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>


typedef struct ListNode {
    struct ListNode *next;
} ListNode;


struct Demo {
    int data;
    ListNode node;
};


int main(int argc, char **argv) {
    struct Demo demo1 = {1, NULL}; 
    struct Demo demo2 = {2, NULL};
    struct Demo demo3 = {3, NULL};




    demo1.node.next = &demo2.node;


    demo2.node.next = &demo3.node; 


    ListNode *node = &demo1.node;
    while (node) {
        struct Demo *demo = (struct Demo*)((char*)node - offsetof(struct Demo, node));
        printf("demo data : %d\n", demo->data);
        node = node->next;
    }   
    
    return 0;
}

Is defined as a normal simple ListNode List data structure will now be defined in the Demo ListNode, each node in accordance ListNode Demo data structure assembly,

While traversing the inquiry has nothing to do with the Demo, only need access to the data members Demo can be directly based on the data structure of the node by node to get offsetof

Published 140 original articles · won praise 28 · views 180 000 +

Guess you like

Origin blog.csdn.net/qq_16097611/article/details/79579658