Tom Winter Tom Winter - 1 year ago 59
C++ Question

call a struct attribute of a struct via pointer arithmetic

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;
}


Hello


  1. How to convert this whole line(if possible) or at least
    Ppy[i]
    to
    Pointer style/arithmetic :
    Als->Ppy[i]->VA2


    Something like this but it doesn't work :
    Als->*(Ppy + i)->VA2

  2. Is there a way to make this even more complex (not
    asm
    deep)?


Answer Source

Instead of:

    Als->Ppy[i]->VA2;

You can write:

   (*(Als->Ppy + i))->VA2;
  • The pointer to the array is Als->Ppy
  • The pointer to an element of the array is Als->Ppy + i
  • The value of an element of the array is *(Als->Ppy + i)

The value of an element of the array is itself a pointer, and you need to wrap the above expression in parens before using it to point to an element of the structure.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download