计算机系统基础
《计算机系统基础》Homework
HW1:数据的表示
题目一:
结果:
所占存储空间
Test1:20
Test2:24
test1 的各分量的偏移量4,8,12
test2 的各分量的偏移量4,8,12
在添加#pragma pack(2)语句之后,添加特殊test3和test4 类
Test3 的各分量的偏移量4,8,12
Test4 的各分量的偏移量4,8,12
过程:使用sizeof()来计算结构体的存储空间,我在网上找到一个函数它的库函数为函数名为offsetof ()可以计算结构体中各分量的偏移量。在结构体test2中的
__attribute__((aligned(8)))的意思为以8字节对齐来让编译器分配存储空间。而#pragma pack(2)语句是以2字节对齐让编译器分配存储空间。
源代码:#include
#include
#include
struct test1{
};
struct test2{
char x2[3]; short x3[2]; int x1; longlong x4; char x2[3]; short x3[2]; int x1; longlong x4;
}__attribute__((aligned(8)));
#pragma pack(2)
struct test3{
};
struct test4{
char x2[3]; short x3[2]; int x1; longlong x4; char x2[3]; short x3[2]; int x1; longlong x4;
}__attribute__((aligned(8)));
int main(){
struct test1 a; struct test2 b; struct test3 c;
printf("Storage space size test1:%d\n",sizeof(a)); printf("Storage space size test2:%d\n",sizeof(b)); printf("the offset test1 x2:%d\n",offsetof(struct test1,x2)); printf("the offset test1 x3:%d\n",offsetof(struct test1,x3)); printf("the offset test1 x1:%d\n",offsetof(struct test1,x1)); printf("the offset test1 x4:%d\n",offsetof(struct test1,x4)); printf("the offset test2 x2:%d\n",offsetof(struct test1,x2)); printf("the offset test2 x3:%d\n",offsetof(struct test1,x3)); printf("the offset test2 x1:%d\n",offsetof(struct test1,x1)); printf("the offset test2 x4:%d\n",offsetof(struct test1,x4)); printf("the offset test3 x2:%d\n",offsetof(struct test1,x2)); printf("the offset test3 x3:%d\n",offsetof(struct test1,x3)); printf("the offset test3 x1:%d\n",offsetof(struct test1,x1)); printf("the offset test3 x4:%d\n",offsetof(struct test1,x4)); printf("the offset test4 x2:%d\n",offsetof(struct test1,x2)); printf("the offset test4 x3:%d\n",offsetof(struct test1,x3)); printf("the offset test4 x1:%d\n",offsetof(struct test1,x1)); printf("the offset test4 x4:%d\n",offsetof(struct test1,x4)); return 0;
题目二:
过程:定义两个int 变量a,b 将两个表达式的结果转为int 型进行输出,然后进行判断,如果-2
结果:
分析:在-2与2进行比较时是有符号的进行比较,两边进行取补,所以-2
源代码:
#include
#include
#include
int main(){
}
题目三:
分析:char 类型的数据占一个字节,也就是8个二进制位,但它表示的是有符号的类型,所以表示的范围是-128~127;
因为-1是在char 表示的范围是-128~127内部,所以c 的机器码为[**************]1 int a; a=(int)(-20) printf("-20) printf("-2
题目四:
分析:因为在union 共用体中,inta 和char b[4]数据公用一段内存地址,当4个字节的int a被赋值之后,char b[4]就公用这四个字节,当输出num.b[2]
时就输出第三个字节中的内容
题目五:
分析:在IOS C90标准下编译器处理常量时将