[C.C++] 【C语言】C tips

322 0
Honkers 2025-5-25 05:36:43 来自手机 | 显示全部楼层 |阅读模式

1. How to solve warning: cast to pointer from integer of different size and vice versa:

  1. #include <stdio.h>
  2. int main() {
  3. void *p = NULL;
  4. int a = 3;
  5. p = (void *)a;
  6. a = (int)p;
  7. printf("%ld\n", p);
  8. printf("%ld\n", a);
  9. return 0;
  10. }
复制代码

The above code has the following warnings when compiling: 

  1. /tmp/0pubXc3fmS.c: In function 'main':
  2. /tmp/0pubXc3fmS.c:7:9: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
  3. 7 | p = (void *)a;
  4. | ^
  5. /tmp/0pubXc3fmS.c:8:9: warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]
  6. 8 | a = (int)p;
  7. | ^
  8. /tmp/0pubXc3fmS.o
复制代码

Converting pointer/data to (unsigned) long before casting to required data types can eliminate this warning: (intptr_t works the same)

  1. #include <stdio.h>
  2. int main() {
  3. void *p = NULL;
  4. int a = 3;
  5. p = (void *)(long)a;
  6. a = (int)(long)p;
  7. printf("%ld\n", p);
  8. printf("%ld\n", a);
  9. return 0;
  10. }
复制代码

2. Access to anonymous union in a struct

If a union in a structure that has no name, you can directly access the fields in the union without the union name:

  1. #include <stdio.h>
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include <stdint.h>
  5. struct ifreq {
  6. union {
  7. short ifru_flags;
  8. int ifru_ivalue;
  9. int ifru_mtu;
  10. };
  11. union {
  12. short ifru_flags2;
  13. int aaa;
  14. int bbb;
  15. };
  16. };
  17. int main()
  18. {
  19. printf("%d\n", sizeof(struct ifreq));
  20. struct ifreq ifr = {0};
  21. printf("ifr.ifru_flags:%.4X\n", ifr.ifru_flags);
  22. ifr.ifru_flags = 0x55A5;
  23. ifr.ifru_flags2 = 0x3344;
  24. ifr.aaa = 0xAABBCCDD;
  25. printf("ifr.ifru_flags:%.4X\n", ifr.ifru_flags);
  26. printf("ifr.ifru_flags2:%.4X\n", ifr.ifru_flags2);
  27. dg_frame_dump((uint8_t *)&ifr, sizeof(ifr));
  28. return 0;
  29. }
复制代码

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

本版积分规则

Honkers

荣誉红客

关注
  • 4013
    主题
  • 36
    粉丝
  • 0
    关注
这家伙很懒,什么都没留下!

中国红客联盟公众号

联系站长QQ:5520533

admin@chnhonker.com
Copyright © 2001-2025 Discuz Team. Powered by Discuz! X3.5 ( 粤ICP备13060014号 )|天天打卡 本站已运行