offsetof获取结构体成员变量

offsetof获取结构体成员变量

代码:

// gcc -Wall -o t t.c 

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

struct Person {
    char name[50];
    int age;
    double score;
};

int main() {
    // 获取结构体成员的偏移量
    size_t offset_name = offsetof(struct Person, name);
    size_t offset_age = offsetof(struct Person, age);
    size_t offset_score = offsetof(struct Person, score);

    printf("Offset of name: %zu\n", offset_name);
    printf("Offset of age: %zu\n", offset_age);
    printf("Offset of score: %zu\n", offset_score);

    struct Person prsn = {"Lilei", 12, 99}  ;

    char * name = (char *)((char*)&prsn + offset_name) ;
    int * age= (int*)((char*)&prsn + offset_age) ;
    double * score = (double *)((char*)&prsn + offset_score) ;


    printf("name  : %s\n", name) ;
    printf("age   : %d\n", *age) ;
    printf("score : %f\n", *score) ;

    return 0;
}

测试:

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注