[ARM入门] 快速获取结构体成员大小

[复制链接]
 楼主| 呐咯密密 发表于 2023-5-29 13:50 | 显示全部楼层 |阅读模式
  1. #include <stdio.h>   

  2. // 获取结构体成员大小
  3. #define  GET_MEMBER_SIZE(type, member)   sizeof(((type*)0)->member)

  4. // 获取结构体成员偏移量
  5. #define  GET_MEMBER_OFFSET(type, member)  ((size_t)(&(((type*)0)->member)))

  6. typedef struct _test_struct0
  7. {
  8. char x;  
  9. char y;
  10. char z;
  11. }test_struct0;

  12. typedef struct _test_struct1
  13. {
  14. char a;  
  15. char c;
  16. short b;         
  17. int d;
  18. test_struct0 e;
  19. }test_struct1;

  20. int main(int arc, char *argv[])
  21. {
  22. printf("GET_MEMBER_SIZE(test_struct1, a) = %ld\n", GET_MEMBER_SIZE(test_struct1, a));
  23.     printf("GET_MEMBER_SIZE(test_struct1, c) = %ld\n", GET_MEMBER_SIZE(test_struct1, c));
  24. printf("GET_MEMBER_SIZE(test_struct1, b) = %ld\n", GET_MEMBER_SIZE(test_struct1, b));
  25. printf("GET_MEMBER_SIZE(test_struct1, d) = %ld\n", GET_MEMBER_SIZE(test_struct1, d));
  26.     printf("GET_MEMBER_SIZE(test_struct1, e) = %ld\n", GET_MEMBER_SIZE(test_struct1, e));
  27.     printf("test_struct1 size = %ld\n", sizeof(test_struct1));

  28. printf("GET_MEMBER_OFFSET(a): %ld\n", GET_MEMBER_OFFSET(test_struct1, a));
  29. printf("GET_MEMBER_OFFSET(c): %ld\n", GET_MEMBER_OFFSET(test_struct1, c));
  30. printf("GET_MEMBER_OFFSET(b): %ld\n", GET_MEMBER_OFFSET(test_struct1, b));
  31. printf("GET_MEMBER_OFFSET(d): %ld\n", GET_MEMBER_OFFSET(test_struct1, d));
  32. printf("GET_MEMBER_OFFSET(e): %ld\n", GET_MEMBER_OFFSET(test_struct1, e));

  33. return 0;
  34. }
复制代码


yangjiaxu 发表于 2023-5-31 08:52 | 显示全部楼层
真不错,这种就可以用已有的库实现获取数组的大小,非常节省时间呢
您需要登录后才可以回帖 登录 | 注册

本版积分规则

认证:苏州澜宭自动化科技嵌入式工程师
简介:本人从事磁编码器研发工作,负责开发2500线增量式磁编码器以及17位、23位绝对值式磁编码器,拥有多年嵌入式开发经验,精通STM32、GD32、N32等多种品牌单片机,熟练使用单片机各种外设。

567

主题

4081

帖子

56

粉丝
快速回复 在线客服 返回列表 返回顶部