如何通过offsetof 动态的给结构体或者类成员变量赋值

来源:互联网 发布:java 校验身份证号码 编辑:程序博客网 时间:2024/05/16 08:28

结构体

typedef struct {

char a;
char b;
int  abc;

}stTest;

代码如下:

int m = offsetof(stTest, abc);
stTest test ;
*(int*)(((char*)(&test))+m) = 1231424;


刚开始我犯了一个错误,错误的写法如下:

*(int*)(((&test))+m) = 1231424;

必须要将(&test)转为char* 再加上成员变量偏移量,才能正确通过地址找到变量位置。

*(int*)(((char*)(&test))+m) = 1231424;

这样才对

0 0
原创粉丝点击