fork download
  1. #include <iostream>
  2. #include <new>
  3. #include <cstring>
  4.  
  5. using namespace std;
  6.  
  7. template <typename STRUCT, typename TYPE> class flex_struct {
  8. flex_struct(){}
  9. public:
  10. //should be safe to access and check what length the array is
  11. static STRUCT* head(char*buff) {
  12. //is this next line wrong?
  13. //if((alignof(STRUCT)%reinterpret_cast<size_t>(buff))!=0) { throw std::exception(); }
  14. return reinterpret_cast<STRUCT*>(buff);
  15. }
  16.  
  17. struct struct_with_array : public STRUCT { TYPE buf[1]; };
  18.  
  19. TYPE* buff() {
  20. //if(length==0) { throw std::exception(); }
  21. auto p = reinterpret_cast<struct_with_array*>(this);
  22. return p->buf;
  23. }
  24. };
  25.  
  26. typedef short testtype;
  27.  
  28. struct MyVariableLengthStruct : public flex_struct<MyVariableLengthStruct, testtype> {
  29. int a, b;
  30. char c;
  31. };
  32.  
  33. struct MyVariableLengthStruct2 {
  34. int a, b;
  35. char c;
  36. testtype buf[1];
  37. };
  38. struct MyVariableLengthStruct3a {
  39. int a, b;
  40. char c;
  41. };
  42. struct MyVariableLengthStruct3 : MyVariableLengthStruct3a {
  43. testtype buf[1];
  44. };
  45. int main() {
  46.  
  47. auto srcarray=new char[1024];
  48. memset(srcarray, 0, sizeof(srcarray)); //whats a C++ way to do this w/o writing a loop or function?
  49. auto v = MyVariableLengthStruct::head(srcarray);
  50. auto buff = v->buff();
  51. auto dif1 = (int)buff-(int)v;
  52. printf("%X %X %d\n", v, buff, dif1);
  53. MyVariableLengthStruct2 v2;
  54. auto dif2 = (int)v2.buf-(int)&v2;
  55. printf("%X %X %d\n", &v2, v2.buf, dif2);
  56. MyVariableLengthStruct3 v3;
  57. auto dif3 = (int)v3.buf-(int)&v3;
  58. printf("%X %X %d\n", &v3, v3.buf, dif3);
  59. }
  60.  
Success #stdin #stdout 0s 2960KB
stdin
Standard input is empty
stdout
8853008 8853012 10
BF9DE184 BF9DE18E 10
BF9DE174 BF9DE180 12