【C语言笔记】【linux宏定义系列】 结构体成员的大小 FIELD_SIZEOF
linux宏定义系列内容。用于记录在linux之中各式各样的宏定义?。
宏定义说明
用于获取结构体成员的大小,占多少个字节。
例如结构体struct type
struct type {
char test_char;
short test_short;
};
其中成员test_char 占一个字节,成员test_short 占两个字节。
该宏定义来自linux kernel 3.10。
实现代码
#define FIELD_SIZEOF(t, f) (sizeof(((t*)0)->f))
宏定义中:
t 表示用于计算的结构体。
f 表示结构体的成员名。
示例程序
定义了一个用于测试的结构体类型struct test_type 。
struct test_type {
int test_int;
short test_short;
char test_char;
long test_long;
float test_float;
double test_double;
int *test_pint;
char *test_pchar;
char test_c[10];
unsigned int test_unsigned_int;
unsigned short test_unsigned_short;
unsigned char test_unsigned_char;
};
int main(int argc, char* argv[])
{
printf("%d\n", FIELD_SIZEOF(struct test_type, test_int));
printf("%d\n", FIELD_SIZEOF(struct test_type, test_short));
printf("%d\n", FIELD_SIZEOF(struct test_type, test_char));
printf("%d\n", FIELD_SIZEOF(struct test_type, test_long));
printf("%d\n", FIELD_SIZEOF(struct test_type, test_float));
printf("%d\n", FIELD_SIZEOF(struct test_type, test_double));
printf("%d\n", FIELD_SIZEOF(struct test_type, test_pint));
printf("%d\n", FIELD_SIZEOF(struct test_type, test_pchar));
printf("%d\n", FIELD_SIZEOF(struct test_type, test_c));
printf("%d\n", FIELD_SIZEOF(struct test_type, test_unsigned_int));
printf("%d\n", FIELD_SIZEOF(struct test_type, test_unsigned_short));
printf("%d\n", FIELD_SIZEOF(struct test_type, test_unsigned_char));
return 0;
}
运行后,结果为
4
2
1
4
4
8
4
4
10
4
2
1
结果与预期一致。
注意,这个结果与使用的平台相关,不同平台计算出来的结果会不一样,我这边是使用的32位机。
实现过程
(sizeof(((t*)0)->f)) 首先通过(t*)0 进行强制类型转换,将0地址强制转换为一个t 类型的指针,然后指针指向结构体的成员f ,再通过sizeof 计算出这个结构体成员的大小。
[参考资料]
linux kernel 3.10
/include/linux/kernel.h
本文链接:https://blog.csdn.net/u012028275/article/details/118864233
|