offsetof(struct stu,ch)is0offsetof(struct stu,sz)is4offsetof(struct stu,age)is8 我们画图验证一下: 三.offsetof的实现 库函数中对offsetof的实现是这样的: 代码语言:javascript 代码运行次数:0 复制 Cloud Studio代码运行 #defineOFFSET(type,member)(size_t)&((type*)0)->member) 我们画图分析一下其中的...
#include<stdio.h>#define offsetof(type, member) (size_t) &((type*)0)->membertypedefstruct{chara;intb;intc;}test;voidmain(void){printf("offset: %ld %ld\r\n",offsetof(test,b),offsetof(test,c));} 输出: offset:48 container_of C语言中有这样一个宏container_of,它的作用是通...
#include<stdio.h>#defineoffsetof(type, member) (size_t) &((type*)0)->membertypedefstruct{chara;intb;intc;}test;voidmain(void){printf("offset: %ld %ld\r\n",offsetof(test,b),offsetof(test,c));} 输出: offset:48 container_of
运行结果如下: offsetof(struct stu,ch) is 0offsetof(struct stu,sz) is 4offsetof(struct stu,age) is 8 我们画图验证一下: 三.offsetof的实现 库函数中对offsetof的实现是这样的: #define OFFSET(type,member) (size_t)&((type*)0)->member) 我们画图分析一下其中的原理: 了解了原理后,我们自己编写...
sizeof( foo ); // error void foo2() { } sizeof( foo2() ); // error struct S { unsigned int f1 : 1; unsigned int f2 : 5; unsigned int f3 : 12; }; sizeof( S.f1 ); // error 3、sizeof的常量性 sizeof的计算发生在编译时刻,所以它可以被当作常量表达式使用,如: ...
container_of函数实现include/linux/kernel.h(不同的内核函数实现会小有不同) /** * container_of - cast a member of a structure out to the containing structure* @ptr: the pointer to the member. * @type: the type of the container struct this is embedded in. * @member: ...
/* 计算member在结构体type中的偏移量 */#defineOFFSET_IN_T(type, member) \(unsignedlong)(&((type*)0)->member) 写个代码实验一下,测试代码如下: #include<stdlib.h>#include<stdio.h>#include<string.h>#defineNAME_MAX_LEN 32typedefstructlist_node{structlist_node*prv;structlist_node*next;}list...
(((STRUCTtype*)0)->member)//不能用成员指针减结构体起始位置地址的方式去计算偏移量// #define OFFSET2(STRUCTname,member) (size_t)(&(STRUCTname.member) - &STRUCTname)intmain(){structAstr={'a',2024};printf("%zd\n",OFFSET1(structA,b));//printf("%zd\n", OFFSET2(str, b));return0...
offset ib is 4 offset dc is 8 2.container_of 是通过结构体的某成员的地址得到整个结构体的地址,在使用上进而可以访问到结构体的其余成员 /** * container_of - cast a member of a structure out to the containing structure * @ptr: the pointer to the member. ...
&( ((type *)0)->member )在最前面有个取地址符&,它的意图是想取member的地址,所以编译器同样会优化为直接取地址。struct apple{ int weight; int color; }; int main(int argc, char *argv[]) { int weight = 5; typeof(((struct apple *)0)->weight) *ap1 = &weight;//定义一个指针变量...