C语言中结构体内存存储方式

C语言中结构体内存存储方式

结构体的默认存储方式采用以最大字节元素字节数对其方式进行对齐,例如一个结构体中定义有char、int类型元素,则结构体存储空间按照int类型占用字节,如果还有double类型元素,则结构体存储空间按double类型占用字节对其。针对该特性特意编写如下测试代码:

​
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
​
int main(int argc, char *argv[]) {
    int i = 0;
    printf("struct test...\r\n"); 
    
    struct _s
    {
  unsigned char elem;   unsigned int elem1;   /*int 存储空间为4字节*/  }s = {3, 4};   struct _t  {   unsigned char elem;   unsigned int elem2;   double elem1;  /*double 存储空间为8字节*/  }t = {8, 9, 9.9};   struct _y  {   unsigned char elem;   double elem1;  /*double 存储空间为8字节*/   unsigned int elem2;  }y;   printf("int char = %d\r\n", sizeof(int)/sizeof(char));  printf("float char = %d\r\n", sizeof(float)/sizeof(char));  printf("double char = %d\r\n", sizeof(double)/sizeof(char));  printf("struct _y char count = %d\r\n", sizeof(struct _y)/sizeof(char));   /* 默认输出 */  printf("struct _s char count = %d\r\n", sizeof(struct _s)/sizeof(char));  for( i=0; i< sizeof(struct _s)/sizeof(char); ++i)   printf("index %d = %d, ", i, *((unsigned char*)(&s)+i));    printf("struct _t char count = %d\r\n", sizeof(struct _t)/sizeof(char));  for( i=0; i< sizeof(struct _t)/sizeof(char); ++i)   printf("index %d = %d, ", i, *((unsigned char*)(&t)+i));    /* 将struct _s的存储空间所有字节赋值为0 */  for( i=0; i< sizeof(struct _s)/sizeof(char); ++i)   *((unsigned char*)(&s)+i) = 0;  s.elem = 2;  s.elem1 = 5;   for( i=0; i< sizeof(struct _t)/sizeof(char); ++i)   *((unsigned char*)(&t)+i) = 0;  t.elem = 8;  t.elem2 = 9.9;  t.elem1 = 6;   printf("\r\nstruct _s char count = %d\r\n", sizeof(struct _s)/sizeof(char));  for( i=0; i< sizeof(struct _s)/sizeof(char); ++i)   printf("index %d = %d, ", i, *((unsigned char*)(&s)+i));    printf("\r\nstruct _t char count = %d\r\n", sizeof(struct _t)/sizeof(char));  for( i=0; i< sizeof(struct _t)/sizeof(char); ++i)   printf("index %d = %d, ", i, *((unsigned char*)(&t)+i));   return 0; }

编译运行上述代码,结构体_s, _t, _y的存储空间分别为8,16,24。对比可知结构体存储空间大小能被结构体空间最大元素占用字节数整除,并且如果相邻元素空间大小累加小于单位最大空间大小,会尝试再次累加,累加如果大于最大空间大小,则选择扩充之前元素的空间大小。

转载于:https://www.cnblogs.com/BlogsOfLei/p/8666194.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值