c语言学习笔记十三

结构体
示例代码
#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;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值