0

I remember on MASM32 compiler the directive ASSUME that let me assume a pointer as a struct. Is any way to do this in C++? For example I want to do this:

char* test = new char [sizeof MyStruct + MAX_REALIGN];
MyStruct* data = test;
data.member = 1;

The reason I need this is because I have a pointer to a struct which I need to recompile with new data, increasing the size of the original struct and realign some of their members. After the recompile is done I will no longer reference to the new struct, I just need the reference before making the recompile.

It sounds a little hard to understand, but the question is quite simple: is there any way to reference a pointer as a struct? (I know its not safe, portable, etc, etc).

ffenix
  • 543
  • 1
  • 5
  • 22

2 Answers2

1

Reinterpret_cast converts any pointer type to any other pointer type, even of unrelated classes.

Jacob Seleznev
  • 8,013
  • 3
  • 24
  • 34
0

MyStruct* data = reinterpret_cast<MyStruct*>(test);

Alternatively, you can use a c-style cast, which is functionally equivalent in this case.

MyStruct* data = (MyStruct*)test;

This is generally dis-recommended because the c-style casts coerce the value into whatever you say. However, that's basically what you're doing with the reinterpret-cast, so the cleaner syntax may be worth it (though I'd question why you're doing it this way to begin with).

Tawnos
  • 1,877
  • 1
  • 17
  • 26
  • I always use C style... Why bother writing so long? – SwiftMango Aug 01 '12 at 23:47
  • The link in my answer explains it a bit, you could also look into it. The short of it is that the c++ style casts will throw compiler errors if you're doing something dangerous inadvertently. – Tawnos Aug 02 '12 at 13:06