I have a testing struct definition as follows:
struct test{ int a, b, c; bool d, e; int f; long g, h; };
And somewhere I use it this way:
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
This works correctly on my Windows – it prints 15 as expected, but is it safe? Can I be really sure the variable is on the spot in memory I want it to be – expecially in case of such combined structs (for example f is on my compiler the fifth word, but it is a sixth variable)?
If not, is there any other way to manipulate struct members directly without actually having struct->member construct in the code?
It looks like you are asking two questions
Is it safe to treat &test as a 3 length int arrray?
It’s probably best to avoid this. This may be a defined action in the C++ standard but even if it is, it’s unlikely that everyone you work with will understand what you are doing here. I believe this is not supported if you read the standard because of the potential to pad structs but I am not sure.
Is there a better way to access a member without it’s name?
Yes. Try using the offsetof macro/operator. This will provide the memory offset of a particular member within a structure and will allow you to correctly position a point to that member.
Another way though would be to just take the address of c directly