通过指针算法调用结构的结构属性

call a struct attribute of a struct via pointer arithmetic

本文关键字:结构 属性 调用 算法 指针      更新时间:2023-10-16
struct Test1 {
struct Test2 {
DWORD VA1 = 0;
DWORD VA2 = 0;
Test2(DWORD hp):VA1(hp) { }
} *Ppy[5];
Test1() {
for (int i = 0; i < 5; i++)
*(Ppy + i) = new Test2((DWORD)i+2);
}
~Test1() {
for (int i = 0; i < 5; i++)
delete *(Ppy + i);
}
};
void main() {
Test1*Als = new Test1;
for (int i = 0; i < 5; i++)
Als->Ppy[i]->VA2;
// doesn't work->  cout << Als->*(Ppy + i)->VA2 << endl;
delete Als;
}

你好

  1. 如何将整行(如果可能(或至少Ppy[i]转换为 指针样式/算术:Als->Ppy[i]->VA2

    像这样的东西,但它不起作用:Als->*(Ppy + i)->VA2

  2. 有没有办法使这更加复杂(不是asm深(?

而不是:

Als->Ppy[i]->VA2;

你可以写:

(*(Als->Ppy + i))->VA2;
  • 指向数组的指针Als->Ppy
  • 指向数组元素的指针Als->Ppy + i
  • 数组元素的值为*(Als->Ppy + i)

数组元素的值本身就是一个指针,在使用它指向结构的元素之前,您需要将上述表达式包装在括号中。