#include <iostream>
#include <new>
#include <cstring>

using namespace std;

template <typename STRUCT, typename TYPE> class flex_struct {
	flex_struct(){}
public:
	//should be safe to access and check what length the array is
	static STRUCT* head(char*buff) {
		//is this next line wrong?
		//if((alignof(STRUCT)%reinterpret_cast<size_t>(buff))!=0) { throw std::exception(); }
		return reinterpret_cast<STRUCT*>(buff);
	}
	
	struct struct_with_array : public STRUCT { TYPE buf[1]; };

	TYPE* buff() {
		//if(length==0) { throw std::exception(); }
		auto p = reinterpret_cast<struct_with_array*>(this);
		return p->buf;
	}
};

typedef short testtype;

struct MyVariableLengthStruct : public flex_struct<MyVariableLengthStruct, testtype> {
	int a, b;
	char c;
};

struct MyVariableLengthStruct2 {
	int a, b;
	char c;
	testtype buf[1];
};
struct MyVariableLengthStruct3a {
	int a, b;
	char c;
};
struct MyVariableLengthStruct3 : MyVariableLengthStruct3a {
	testtype buf[1];
};
int main() {

	auto srcarray=new char[1024];
	memset(srcarray, 0, sizeof(srcarray)); //whats a C++ way to do this w/o writing a loop or function?
	auto v = MyVariableLengthStruct::head(srcarray);
	auto buff = v->buff();
	auto dif1 = (int)buff-(int)v;
	printf("%X %X %d\n", v, buff, dif1);
	MyVariableLengthStruct2 v2;
	auto dif2 = (int)v2.buf-(int)&v2;
	printf("%X %X %d\n", &v2, v2.buf, dif2);
	MyVariableLengthStruct3 v3;
	auto dif3 = (int)v3.buf-(int)&v3;
	printf("%X %X %d\n", &v3, v3.buf, dif3);
}
