根据结构体成员地址获结构体地址

发布时间 2023-03-23 22:21:36作者: weixicai

在同一台机器上,结构体的在内存中分配每个成员变量的偏移地址固定的。

struct fox {
    unsigned long tail_length;
    unsigned long weight;
    _Bool is_fantastic;
    int length;
};

 

struct fox *a_fox=(struct fox *)malloc(sizeof(struct fox));

&a_fox->length - &a_fox->tail_length = (size_t) &((struct fox *)0)->tail_length; 该结构体分配的位置不影响偏移量的值。

若&a_fox->tail_length已知,那么(struct fox *)&a_fox->tail_length就是结构体初始地址,