如何通過offsetof 動態的給結構體或者類成員變量賦值

結構體

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;

這樣纔對

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章