/*
题目名称:offsetof宏
题目内容 :
写一个宏,计算结构体中某变量相对于首地址的偏移,并给出说明
考察 : offseto宏的实现
*/
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <stddef.h> //offsetof宏所需
#define MY_OFFSETOF(STRUCT_NAME, MEM_NAME) (int)&(((STRUCT_NAME*)0)->MEM_NAME)
struct A
{
int a;
char b;
float c;
char d;
char e;
};
int main()
{
printf("%d\n", offsetof(struct A, a));
printf("%d\n", offsetof(struct A, b));
printf("%d\n", offsetof(struct A, c));
printf("%d\n", offsetof(struct A, d));
printf("%d\n\n", offsetof(struct A, e));
printf("%d\n", MY_OFFSETOF(struct A, a));
printf("%d\n", MY_OFFSETOF(struct A, b));
printf("%d\n", MY_OFFSETOF(struct A, c));
printf("%d\n", MY_OFFSETOF(struct A, d));
printf("%d\n\n", MY_OFFSETOF(struct A, e));
printf("%d", sizeof(struct A));
return 0;
}
c语言-计算结构体中某变量相对于首地址的偏移(模拟offsetof宏)
最新推荐文章于 2022-09-06 20:07:18 发布