企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持知识库和私有化部署方案 广告
[TOC] # 结构体指针偏移 指针改变类型,改变的是步长,offset算出这个值的偏移量,算好后,再转换为他的类型的指针 ~~~ struct Teacher { char a1; int a2; }; int main() { Teacher t = Teacher{'1', 222111}; //#include <stddef.h> int res = *((int *) ((char *) &t + offsetof(Teacher, a2))); printf("%d\n", res); getchar(); return 0; } ~~~ ~~~ struct C { int a; double b; }; struct B { char a; char b; struct C c; }; int main() { struct B b = {'a', 20 , 30, 3.14}; int off1 = offsetof(struct B, c); int off2 = offsetof(struct C, b); printf("%f\n", *(double *)(((char *)&b + off1) + off2)); printf("%f\n", b.c.b); printf("%f\n", ((struct C *)((char *)&b + off1))->b); getchar(); return 0; } ~~~