Chinaunix首页 | 论坛 | 博客
  • 博客访问: 118776
  • 博文数量: 29
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 115
  • 用 户 组: 普通用户
  • 注册时间: 2015-11-17 09:35
文章分类

全部博文(29)

文章存档

2018年(5)

2016年(10)

2015年(14)

我的朋友

分类: C/C++

2018-03-05 20:09:56


分别对#pragma pack(1)和#pragma pack(8)进行了测试。

测试平台:Ubuntu 15.04,32位
GCC版本:4.9.2

测试代码:

点击(此处)折叠或打开

  1. #include <stdio.h>

  2. // #pragma pack(8)
  3. #pragma pack(1)
  4. typedef struct s1{
  5.     short a;
  6.     long b;
  7. } S1;

  8. typedef struct s2{
  9.     char c;
  10.     S1 d;
  11.     long long e;
  12. } S2;
  13. #pragma pack()

  14. int main(void)
  15. {
  16.     S1 s1 = {0xEEFF, 0xAABBCCDD};
  17.     S2 s2 = {0x11, {0x2233, 0x44556677}, 0x8899EEFF};
  18.     int s1_size = sizeof(s1);
  19.     int s2_size = sizeof(s2);
  20.     int i;
  21.     unsigned char *s1_p = (unsigned char *)&s1;
  22.     unsigned char *s2_p = (unsigned char *)&s2;
  23.     
  24.     printf("char:%d, short:%d, int:%d, long:%d, long long:%d, float:%d, double:%d\n",
  25.         sizeof(char), sizeof(short), sizeof(int), sizeof(long), sizeof(long long), \
  26.         sizeof(float), sizeof(double));
  27.     
  28.     printf("s1 addr: %08x, s2 addr: %08x\n", (unsigned int)s1_p, (unsigned int)s2_p);
  29.     printf("s1 size: %d byte\n", s1_size);
  30.     for(i = 0; i < s1_size; i++) {
  31.         printf("%02x ", s1_p[i]);
  32.     }
  33.     printf("\n");
  34.     
  35.     printf("s2 size: %d byte\n", s2_size);
  36.     for(i = 0; i < s2_size; i++) {
  37.         printf("%02x ", s2_p[i]);
  38.     }
  39.     printf("\n");
  40.     
  41.     return 0;
  42. }
#pragma pack(1)测试结果:

#pragma pack(8)测试结果:

参考:
[1] http://blog.csdn.net/lime1991/article/details/44536343
[2] http://blog.csdn.net/21aspnet/article/details/6730124
阅读(1530) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~