要求:在linux-gcc下完成以下题目,熟悉整数数值在计算机内部的表示方式。
预备知识:
1.gcc常用指令及相关知识
2.C语言:offsetof()的用法
3.细说 #pragma pack(n) (attribute((aligned(8)))的作用;"__"是两个下划线)
- 下述两个结构所占存储空间多大?结构中各分量所在位置相对于结构起始位置的偏移量是多少?请编写程序以验证你的答案。若使用#pragma pack(2)语句,则结果又如何?
struct test1
{
char x2[3];
short x3[2];
int x1;
long long x4;
};
struct test2
{
char x2[3];
short x3[2];
int x1;
long long x4;
}__attribute__((aligned(8)));
实验过程:
代码如下:
#include<stdio.h>
#include<stdlib.h>
#include<stddef.h>
//#include pragma pace(2) //只需解除注释这一行即可完成第二问
struct test1
{
char x2[3];
short x3[2];
int x1;
long long x4;
};
struct test2
{
char x2[3];
short x3[2];
int x1;
long long x4;
}__attribute__((aligned(8)));
int main()
{
printf("size of test1: %ld\n",sizeof(struct test1));
printf("size of test2: %ld\n",sizeof(struct test2));
printf("pos of test1.x2: %d\n",(int)offsetof(struct test1,x2));
printf("pos of test1.x3: %d\n",(int)offsetof(struct test1,x3));
printf("pos of test1.x1: %d\n",(int)offsetof(struct test1,x1));
printf("pos of test1.x4: %d\n",(int)offsetof(struct test1,x4));
printf("pos of test2.x2: %d\n",(int)offsetof(struct test2,x2));
printf("pos of test2.x3: %d\n",(int)offsetof(struct test2,x3));
printf("pos of test2.x1: %d\n",(int)offsetof(struct test2,x1));
printf("pos of test2.x4: %d\n",(int)offsetof(struct test2,x4));
return 0;
}
实验结果:
//#include pragma pace(2)
#include pragma pace(2)
解释:
我选择去问teacher,有懂的大佬可以在评论区回复,会及时更改。
参考:
如何知道结构体中某个成员相对于结构体||类起始位置的偏移量
关于C语言中结构体所占空间大小的问题汇总