c语言学习笔记十三

本文深入探讨了C语言中的结构体和联合体,包括成员变量的内存布局、如何通过合理安排成员顺序减少填充字节以提高效率,以及联合体内部成员共享同一段内存的特点。此外还介绍了C语言中的内联汇编示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

结构体 
  示例代码
#include<stdio.h>
 int main(void){
struct{
     charo a;
         short b;
            int c;
            char d;
        }s;
s.a=1;
s.b=2;
        s.c=3;
        s.d=4;
printf("%u\n",sizeof(s));
return 0;
 }
  编译:gcc test.c -o
  反汇编:objdump test
 四个成员变量在栈上的排列
 80483ed: c6 44 24 14 01       movb   $0x1,0x14(%esp)
 80483f2: 66 c7 44 24 16 02 00 movw   $0x2,0x16(%esp)
 80483f9: c7 44 24 18 03 00 00 movl   $0x3,0x18(%esp)
 8048400: 00 
 8048401: c6 44 24 1c 04       movb   $0x4,0x1c(%esp)


 合理安排成员顺序,可以避免产生填充字节:
   示例代码:
   方式一:
    struct{
  char a;
        char d;
        short b;
      int c;
    }s;
   方式二(效率有问题不建议使用)
   struct{
  char a;
        short b;
        int c;
        char d;
   }__attribute__((packed))s;




联合体
 示例代码如下:
#include<stdio.h>
typedef union{
  struct{
    unsigned int one:1;
           unsigned int two:3;
           unsigned int three:10;
    unsigned int four:5;
           unsigned int :2;
           unsigned int five:8;
           unsigned int six:8;
        }bitfield;
unsigned char byte[8];
 }demo_type;


 int main(void){
  demo_type u={{1,5,513,17,129,0x81}};
        printf("sizeof demo_type=%u\n",sizeof(demo_type));
         printf("values: u=%u,%u,%u,%u,%u,%


u\n",u.bitfield.one,u.bitfield.two,u.bitfield.three,u.bitfield.four,u.bitfi


eld.five,u.bitfield.six);
 
         printf("hex dump of u: %x %x %x %x %x %x\n",u.byte[0],u.byte


[1],u.byte[2],u.byte[3],u.byte[4],u.byte[5],u.byte[6],u.byte[7]);
        return 0;
 
 }
 




c内联汇编
示例代码:(将a的值赋值给b )
#include<stdio.h>
int main(){
int a=10,b;
        __asm__(
           "movl %1, %%eax\n\t"
           "movl %%eax, %0\n\t"
           /*运算结果输出到b操作数中*/
           :"=r"(b)
           /*从a中获得输入*/
           :"r"(a)
      
     /*汇编指令中被修改过的寄存器列表*/
           :"%eax"       
        );
printf("Result:%d %d\n",a,b);
        return 0;

转载于:https://www.cnblogs.com/retacn-yue/archive/2012/09/20/2761238.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值