C语言typeof详解offsetof

it2022-05-05  145

http://blog.chinaunix.net/uid-28458801-id-4200573.html

 

前言:    typeof关键字是C语言中的一个新扩展,这个特性在linux内核中应用非常广泛。一,说明    typeof的参数可以是两种形式:表达式或类型。    1,表达式的的例子:        typeof(x[0](1)        这里假设x是一个函数指针数组,这样就可以得到这个函数返回值的类型了。        如果将typeof用于表达式,则该表达式不会执行。只会得到该表达式的类型。        以下示例声明了int类型的var变量,因为表达式foo()是int类型的。由于表达式不会被执行,所以不会调用foo函数。            extern int foo();            typeof(foo()) var;    2,参数的例子:        typeof(int *) a,b;            等价于:            int *a,*b;二,实例    1,把y定义成x指向的数据类型:           typeof(*x) y;    2,把y定义成x指向数据类型的数组:           typeof(*x) y[4];    3,把y定义成一个字符指针数组:            typeof(typeof(char *)[4] y;    这与下面的定义等价:            char *y[4];    4,typeof(int *) p1,p2; /* Declares two int pointers p1, p2 */            int *p1, *p2;    5,typeof(int) *p3,p4;/* Declares int pointer p3 and int p4 */            int *p3, p4;    6,typeof(int [10]) a1, a2;/* Declares two arrays of integers */            int a1[10], a2[10];三,局限    typeof构造中的类型名不能包含存储类说明符,如extern或static。不过允许包含类型限定符,如const或volatile。    例如,下列代码是无效的,因为它在typeof构造中声明了extern:        typeof(extern int) a;四,文件参考    1,http://blog.csdn.net/wslong/article/details/7728811    2,http://gcc.gnu.org/onlinedocs/gcc/Typeof.html#Typeof

 

http://blog.csdn.net/firetaker/article/details/7381247

offsetof  :    Retrieves the offset of a member from the beginning of its parent structure.

size_t offsetof(structName, memberName);

Parameters:    structName : Name of the parent data structure.    memberName :Name of the member in the parent data structure for which to determine the offset.

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.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.

 

 #define offsetof(s, m)   (size_t)&(((s *)0)->m)s是一个结构名,它有一个名为m的成员(s和m 是宏offsetof的形参,它实际是返回结构s的成员m的偏移地址.(s *)0 是骗编译器说有一个指向类(或结构)s的指针,其地址值0 &((s *)0)->m   是要取得类s中成员变量m的地址. 因基址为0,这时m的地址当然就是m在s中的偏移最后转换size_t 型,即unsigned int

转载于:https://www.cnblogs.com/virusolf/p/5231037.html


最新回复(0)