电子产业一站式赋能平台

PCB联盟网

搜索
查看: 201|回复: 0
收起左侧

一些实用的嵌入式 C 代码片段!

[复制链接]

520

主题

520

帖子

3477

积分

四级会员

Rank: 4

积分
3477
发表于 2024-8-13 11:38:00 | 显示全部楼层 |阅读模式

2ef01tdv0pc6407780615.gif

2ef01tdv0pc6407780615.gif

快速获取结构体成员大小及偏移量获取结构体成员大小及偏移量的方式有多种。最简便的方式:
代码:
// 微信公众号:嵌入式大杂烩
#include   
// 获取结构体成员大小
#define  GET_MEMBER_SIZE(type, member)   sizeof(((type*)0)->member)
// 获取结构体成员偏移量
#define  GET_MEMBER_OFFSET(type, member)  ((size_t)(&(((type*)0)->member)))
typedef struct _test_struct0
{
char x;  
char y;
char z;
}test_struct0;
typedef struct _test_struct1
{
char a;  
char c;
short b;         
int d;
test_struct0 e;
}test_struct1;
int main(int arc, char *argv[])
{
printf("GET_MEMBER_SIZE(test_struct1, a) = %ld
", GET_MEMBER_SIZE(test_struct1, a));
    printf("GET_MEMBER_SIZE(test_struct1, c) = %ld
", GET_MEMBER_SIZE(test_struct1, c));
printf("GET_MEMBER_SIZE(test_struct1, b) = %ld
", GET_MEMBER_SIZE(test_struct1, b));
printf("GET_MEMBER_SIZE(test_struct1, d) = %ld
", GET_MEMBER_SIZE(test_struct1, d));
    printf("GET_MEMBER_SIZE(test_struct1, e) = %ld
", GET_MEMBER_SIZE(test_struct1, e));
    printf("test_struct1 size = %ld
", sizeof(test_struct1));
printf("GET_MEMBER_OFFSET(a): %ld
", GET_MEMBER_OFFSET(test_struct1, a));
printf("GET_MEMBER_OFFSET(c): %ld
", GET_MEMBER_OFFSET(test_struct1, c));
printf("GET_MEMBER_OFFSET(b): %ld
", GET_MEMBER_OFFSET(test_struct1, b));
printf("GET_MEMBER_OFFSET(d): %ld
", GET_MEMBER_OFFSET(test_struct1, d));
printf("GET_MEMBER_OFFSET(e): %ld
", GET_MEMBER_OFFSET(test_struct1, e));
return 0;
}
运行结果:
回复

使用道具 举报

发表回复

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则


联系客服 关注微信 下载APP 返回顶部 返回列表