C/C++ offsetof

offsetof宏用于获取结构体成员相对于结构体起始位置的字节偏移量。它返回一个size_t类型的值,表示指定成员在类型structName中的偏移。参数包括父结构体的名称和要获取偏移量的成员名。offsetof不适用于位字段,且不是一个函数,不能用C语言的原型来描述。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

offsetof

Retrieves the offset of a member from the beginning of its parent structure.返回结构成员相对于结构开头的字节偏移量。

size_t offsetof( structName, memberName );

RoutineRequired HeaderCompatibility
offsetof<stddef.h>ANSI, Win 95, Win NT

For additional compatibility information, see Compatibility in the Introduction.

Libraries

LIBC.LIBSingle thread static library, retail version
LIBCMT.LIBMultithread static library, retail version
MSVCRT.LIBImport library for MSVCRT.DLL, retail version

Return Value

offsetof returns the offset in bytes of the specified member from the beginning of its parent data structure. It is undefined for bit fields.该宏返回类型为 size_t 的值,表示 type 中成员的偏移量。

Parameters

structName

Name of the parent data structure

memberName

Name of the member in the parent data structure for which to determine the offset

Remarks

The offsetof macro returns the offset in bytes of memberName from the beginning of the structure specified by structName. You can specify types with the struct keyword.

Note   offsetof is not a function and cannot be described using a C prototype.


e.g:

#include "stdafx.h"
#include "stddef.h"
#include "Afx.h"


typedef struct STUDENT_INFO
{
	CString csName;
	unsigned int wID;
	int iarrScore[3];	
	unsigned int wRanking;
}STUDENT;

int main()
{
    printf("STUDENT 结构中的 csName 偏移 %d 字节。\n",offsetof(STUDENT,csName));
    printf("STUDENT 结构中的 wID 偏移 %d 字节。\n",offsetof(STUDENT,wID));
    printf("STUDENT 结构中的 iarrScore 偏移 %d 字节。\n",offsetof(STUDENT,iarrScore));
	printf("STUDENT 结构中的 wRanking 偏移 %d 字节。\n",offsetof(STUDENT,wRanking));

	return true;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值