当前位置: 首页 > news >正文

c语言——宏offsetof

1.介绍

!!! offsetof 是一个

2.使用举例

结构体章节的计算结构体占多少字节需要先掌握(本人博客结构体篇章中已经讲解过)

计算结构体中某变量相对于首地址的偏移,并给出说明

首先,结构体首个变量偏移量为0,假定将首元素的首地址在0处,那么往后每个元素的偏移量就为每个元素的地址,这样一来,取地址就可获得偏移量
#include<stdio.h>
#include<stddef.h>//头函数
struct stu
{
    int a;
    int b;
    char c;
    double d;
};
int main()
{
    printf("%d\n", sizeof(struct stu));//计算总共占用多少字节
    printf("%d\n", offsetof(struct stu,a));//计算偏移量
    printf("%d\n", offsetof(struct stu, b));
    printf("%d\n", offsetof(struct stu, c));
    printf("%d\n", offsetof(struct stu, d));
    return 0;
}

 运行结果:

 

3.模拟实现

#include <stddef.h>
//写一个宏,计算结构体中某变量相对于首地址的偏移,并给出说明
struct stu
{
    int a;
    int b;
    char c;
    double d;
};

#define OFFSETOF(struct_type, mem_name)      (int)&(((struct_type*)0)->mem_name)


int main()
{
    printf("%d\n", OFFSETOF(struct stu, a));
    printf("%d\n", OFFSETOF(struct stu, b));
    printf("%d\n", OFFSETOF(struct stu, c));
    printf("%d\n", OFFSETOF(struct stu, d));

    return 0;
}
 

http://www.lryc.cn/news/352611.html

相关文章:

  • C#串口通信-串口相关参数介绍
  • 节省时间与精力:用BAT文件和任务计划器自动执行重复任务
  • 一年前的Java作业,模拟游戏玩家战斗
  • C++ 学习 关于引用
  • BERT ner 微调参数的选择
  • 【MySQL精通之路】系统变量-持久化系统变量
  • fdk-aac将aac格式转为pcm数据
  • 【C语言深度解剖】(15):动态内存管理和柔性数组
  • 力扣每日一题 5/25
  • (1)无线电失控保护(一)
  • 基于51单片机的多功能万年历温度计—可显示农历
  • 【软件设计师】下午题总结-数据流图、数据库、统一建模语言
  • CSDN 自动评论互动脚本
  • Tomcat端口配置
  • SpringBoot中使用AOP实现日志记录功能
  • kubernetes(k8s) v1.30.1 helm 集群安装 Dashboard v7.4.0 可视化管理工具 图形化管理工具
  • CS144(所有lab解析)
  • LeetCode 热题 100 介绍
  • Flutter 中的 AnimatedPhysicalModel 小部件:全面指南
  • 第二十届文博会沙井艺立方分会场启幕!大咖齐打卡!
  • 【Vue】computed 和 methods 的区别
  • HarmonyOS 鸿蒙应用开发 - 创建自定义组件
  • 【Vue3】封装axios请求(cli和vite)
  • Java8 Optional常用方法使用场景
  • isscc2024 short course4 In-memory Computing Architectures
  • ubuntu 安装 kvm 启动虚拟机
  • [OpenGL] opengl切线空间
  • SpringCloud微服务03-微服务保护-分布式事务-MQ基础-MQ高级
  • 住宅IP?
  • SpringBoot实现邮箱验证码