C/C++ offsetof

offsetof

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

size_t offsetof( structName, memberName );

Routine Required Header Compatibility
offsetof <stddef.h> ANSI, Win 95, Win NT

For additional compatibility information, see Compatibility in the Introduction.

Libraries

LIBC.LIB Single thread static library, retail version
LIBCMT.LIB Multithread static library, retail version
MSVCRT.LIB Import 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;
}

猜你喜欢

转载自blog.csdn.net/gordennizaicunzai/article/details/80960159