我有一个测试结构定义如下:
struct test{
int a, b, c;
bool d, e;
int f;
long g, h;
};
Run Code Online (Sandbox Code Playgroud)
在某个地方我用这种方式:
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
Run Code Online (Sandbox Code Playgroud)
这在我的Windows上正常工作 - 它按预期打印15,但它是否安全?我是否可以确定变量是在内存中我想要的 - 特别是在这种组合结构的情况下(例如f在我的编译器上是第五个字,但它是第六个变量)?
如果没有,有没有其他方法直接操作struct成员而不在代码中实际拥有struct-> member构造?
Jar*_*Par 13
看起来你在问两个问题
治疗和测试作为3长度的安全是否安全?
最好避免这种情况.这可能是C++标准中定义的操作,但即使是这样,与您合作的每个人都不太可能理解您在此处所做的事情.我相信如果你阅读标准是不支持的,因为有可能填充结构,但我不确定.
没有它的名字,是否有更好的方式来访问会员?
是.尝试使用offsetof宏/运算符.这将提供结构中特定成员的内存偏移量,并允许您将点正确定位到该成员.
size_t offset = offsetof(mystruct,c);
int* pointerToC = (int*)((char*)&someTest + offset);
Run Code Online (Sandbox Code Playgroud)
另一种方法是直接获取c的地址
int* pointerToC = &(someTest->c);
Run Code Online (Sandbox Code Playgroud)