Actual total size of struct's members
c, c++, data-structures
Solution
Just save each member of the struct one at a time. If you overload << to write a variable to a file, you can have
myfile << mystruct.member1 << mystruct.member2;
Then you could even overload << to take an entire struct, and do that inside the struct's operator<<, so in the end you have:
myfile << mystruct;
Resulting in save code that looks like:
myfile << count;
for (int i = 0; i < count; ++i)
myFile << data[i];
IMO all that fiddling about with memory addresses and memcpy is too much of a headache when you could do it this way. This general technique is called serialization - hit google for more, it's a well-developed area.
Problem
I must write array of struct Data to hard disk: ``` struct Data { char cmember; /* padding bytes */ int imember; }; ``` ` AFAIK, most of compilers will add some padding bytes between cmember and imember members of Data, but I want save to file only actual data (without paddings). I have next code for saving Datas array (in buffer instead of file for simplification): ``` bool saveData(Data* data, int dataLen, char* targetBuff, int buffLen) { int actualLen = sizeof(char) + sizeof(int); // this code force us to know internal // representation of Data structure int actualTotalLen = dataLen * actualLen; if(actualTotalLen > buffLen) { return false; } for(int i = 0; i < dataLen; i++) { memcpy(targetBuff, &data[i].cmember, sizeof(char)); targetBuff += sizeof(char); memcpy(targetBuff, &data[i].imember, sizeof(int)); targetBuff += sizeof(int); } return true; } ``` ` As you can see, I calculate actual size of Data struct with the code: `int actualLen = sizeof(char) + sizeof(int)`. Is there any alternative to this ? (something like `int actualLen = actualSizeof(Data)`) P.S. this is synthetic example, but I think you understand idea of my question...