`

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;
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics