- C 标准库
- C 库 - 首页
- C 库 - <assert.h>
- C 库 - <complex.h>
- C 库 - <ctype.h>
- C 库 - <errno.h>
- C 库 - <fenv.h>
- C 库 - <float.h>
- C 库 - <inttypes.h>
- C 库 - <iso646.h>
- C 库 - <limits.h>
- C 库 - <locale.h>
- C 库 - <math.h>
- C 库 - <setjmp.h>
- C 库 - <signal.h>
- C 库 - <stdalign.h>
- C 库 - <stdarg.h>
- C 库 - <stdbool.h>
- C 库 - <stddef.h>
- C 库 - <stdio.h>
- C 库 - <stdlib.h>
- C 库 - <string.h>
- C 库 - <tgmath.h>
- C 库 - <time.h>
- C 库 - <wctype.h>
- C 标准库资源
- C 库 - 快速指南
- C 库 - 有用资源
- C 库 - 讨论
C 库 - offsetof() 宏
C 库的 offsetof(type, member-designator) 宏生成一个类型为 size_t 的常量整数,表示结构体成员从结构体开头处的偏移量(以字节为单位)。成员由 member-designator 指定,结构体名称由 type 指定。
此宏通常用于像链表这样的数据结构中。
语法
以下是 C 库中 offsetof() 宏的语法:
offsetof(type, member-designator)
参数
此函数仅接受两个参数:
type − 这是 member-designator 为有效成员指定符的类类型。
member-designator − 这是类类型的成员指定符。
返回值
此宏返回类型为 size_t 的值,该值是成员在 type 中的偏移量。
示例 1
以下 C 库程序说明了 offsetof() 宏的使用。
#include <stddef.h>
#include <stdio.h>
struct address {
char name[50];
char street[50];
int phone;
};
int main () {
printf("name offset = %d byte in address structure.\n",
offsetof(struct address, name));
printf("street offset = %d byte in address structure.\n",
offsetof(struct address, street));
printf("phone offset = %d byte in address structure.\n",
offsetof(struct address, phone));
return(0);
}
输出
执行上述代码后,我们得到以下结果:
name offset = 0 byte in address structure. street offset = 50 byte in address structure. phone offset = 100 byte in address structure.
示例 2
以下示例说明了 offsetof() 宏的重要性,它对于创建数据结构(链表)很有用。
#include <stdio.h>
#include <stddef.h>
struct Node {
int data;
struct Node* next;
};
int main() {
size_t offset = offsetof(struct Node, data);
printf("Offset of 'data' in Node: %zu bytes\n", offset);
return 0;
}
输出
执行上述代码后,我们得到以下结果:
Offset of 'data' in Node: 0 bytes
示例 3
该程序演示了如何使用 offsetof() 宏查找结构体中特定成员的偏移量。
#include <stdio.h>
#define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT))
typedef struct tutorialspoint
{
int i;
double d;
char z;
} tutortype;
int main()
{
printf("%lu", OFFSETOF(tutortype, z));
getchar();
return 0;
}
输出
上述代码产生以下结果:
16
广告