次のようなテスト構造体定義があります。
struct test{
int a, b, c;
bool d, e;
int f;
long g, h;
};
そして、どこかで私はそれをこのように使用しています:
test* t = new test; // create the testing struct
int* ptr = (int*) t;
ptr[2] = 15; // directly manipulate the third word
cout << t->c; // look if it really affected the third integer
これは私の Windows では正しく動作します。期待どおりに 15 が出力されますが、安全ですか? 変数がメモリ内のその場にあることを本当に確信できますか-特にそのような結合された構造体の場合(たとえば、f はコンパイラの 5 番目の単語ですが、6 番目の変数です)?
そうでない場合、実際にコードに struct->member 構造を持たずに構造体メンバーを直接操作する方法はありますか?