您的位置:首页 > 其它

C和指针之结构体大小和成员变量位置距离结构开始存储的位置偏移字节

2017-11-27 22:41 399 查看

1、问题

1)、结构体大小

   结构体成员的内存分配满足下面三个条件

  2 结构体第一个成员的地址和结构体的首地址相同

  3 结构体每个成员地址相对于结构体首地址的偏移量是该成员大小的整数倍,如果不是则编译器会在成员之间添加填充字节

  4 结构体总的大小要是其成员中最大size的整数倍,如果不是编译器会在其末尾添加填充字节

2)、成员变量位置距离结构开始存储的位置偏移字节

我们用offsetof函数

2、测试Demo

#include <stdio.h>
#include <stddef.h>

#define PRODUCT_SIZE 20

struct A
{
int a;
char b;
char d;
};

struct AA
{
char a;
int b;
char c;
};

struct B
{

char a;
double b;
char c;
char d[9];
int e;
};

typedef struct
{
char product[PRODUCT_SIZE];
int qunatity;
float unit_price;
float total_amount;
char s;
} Transaction;

struct C
{
int a;
char b;
short c;
double d;
int f;
};

int main()
{
printf("float size is %d\n", sizeof(float));
printf("short size is %d\n", sizeof(short));
printf("long size is %d\n", sizeof(long));
printf("double size is %d\n", sizeof(double));

//结构体每个成员地址相对于结构体首地址的偏移量是该成员大小的整数倍,如果不是则编译器会在成员之间添加填充字节
//结构体总的大小要是其基本数据成员中最大size的整数倍,如果不是编译器会在其末尾添加填充字节
printf("A size is %d\n", sizeof(struct A));
printf("AA size is %d\n", sizeof(struct AA));
printf("B size is %d\n", sizeof(struct B));
printf("C size is %d\n", sizeof(struct C));
//offsetof表示这个指定成员开始存储的位置距离结构开始存储的位置偏移几个字节
printf("B a offsetof is %d\n", offsetof(struct B, a));
printf("B b offsetof is %d\n", offsetof(struct B, b));
printf("B c offsetof is %d\n", offsetof(struct B, c));
printf("B d offsetof is %d\n", offsetof(struct B, d));
printf("B e offsetof is %d\n", offsetof(struct B, e));

printf("Transaction size is %d\n", sizeof(Transaction));
printf("C produce offsetof is %d\n", offsetof(Transaction, product));
printf("C qunatity offsetof is %d\n", offsetof(Transaction, qunatity));
printf("C unit_price offsetof is %d\n", offsetof(Transaction, unit_price));
printf("C total_amount offsetof is %d\n", offsetof(Transaction, total_amount));
printf("C s offsetof is %d\n", offsetof(Transaction, s));
return 0;
}

3、运行结果

float size is 4
short size is 2
long size is 8
double size is 8
A size is 8
AA size is 12
B size is 32
C size is 24
B a offsetof is 0
B b offsetof is 8
B c offsetof is 16
B d offsetof is 17
B e offsetof is 28
Transaction size is 36
C produce offsetof is 0
C qunatity offsetof is 20
C unit_price offsetof is 24
C total_amount offsetof is 28
C s offsetof is 32
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐