C/C++结构体对齐测试

 
#include <stddef.h>
#include <iostream>
struct s1{    
  int a;    
  int b;
};

#pragma pack(8)
struct s2{    
  char c;    
  int a;    
  double b;
};

struct s3 {    
  char b[10];    
  double a;
};

#pragma unpackstruct s4 {    
  char c;    
  int a;    
  double b;
};

#pragma pack(1)
struct SSS{       /* 13 bytes */    
  char c;    int b;    
  double a;};

#pragma unpack            
struct foo12 {           
  /* 子结构体要求父结构体适用相同的对齐大小  */    
  struct foo12_inner {        
    char *p; /* 8 bytes */        
    int x; /* 4 bytes */        
    char pad[4]; /* 4 bytes */    
  } inner;    
  char c; /* 1 byte*/    
  char pad[7]; /* 7 bytes */
 };/* 结构体的内存对齐,变量的起始地址偏移为 n * min(sizeof(type), pragma pack size) */

union u1 {    
  char a[14];    
  int b;
};

union u2 {    
  char a[17];    
  double b;
};
/* union 的对齐简直不懂 ??   union 同时间只能有一个部分被使用, 因此总的空间要能够提供给每个部分,同时总的空间要与最大的空间对齐 */

int main() {    
  std::cout << "sizeof s1 " << sizeof(s1) << std::endl              
    << "sizeof s2 " << sizeof(s2) << std::endl              
    << "sizeof s3 " << sizeof(s3) << std::endl              
    << "sizeof s4 " << sizeof(s4) << std::endl              
    << "sizeof u1 " << sizeof(u1) << std::endl                     
    << "sizeof u2 " << sizeof(u2) << std::endl                                            
    << std::endl;    
    return 0;
}
 
sizeof s1 8
sizeof s2 16
sizeof s3 24
sizeof s4 16
sizeof u1 16
sizeof u2 24
  

 

 C结构体对齐测试

C++结构体对齐测试

 

posted @ 2024-06-04 09:40  by_mzy  阅读(12)  评论(0编辑  收藏  举报