I have created a struct which contains a character array of size 10 and an integer number. After initializing and populating the struct as an array of size [3] I saved it into a binary file. I also know that we can calculate the size of the struct by just adding the sizes of its elements, in this case char name[10];// = 10 bytes and int age;// = 4 bytes so in total the size of struct student = 10 + 4 = 14 bytes, this means that the size of the array newStudent[3] ={{"joseph",20}, {"yonas",30},{"miryam",40}}; //= 14 * 3 = 42 bytes
Check out the code below.
struct student{
char name[10];
int age;
};
int main()
{
student newStudent[3] ={{"joseph",20}, {"yonas",30},{"miryam",40}};
fstream newFile;
newFile.open("/Users/josephfeleke/Desktop/abeltest/file.bin", ios::out | ios::binary);
if(newFile.is_open()){
newFile.write(reinterpret_cast<char*>(newStudent), 3 * sizeof(student));
}else cout<<"faild to open file";
}
Then i opened the binary file to check the actual bytes stored which are:
01101010 01101111 01110011 01100101 01110000 01101000 00000000 00000000
00000000 00000000 00000000 00000000 00010100 00000000 00000000 00000000
01111001 01101111 01101110 01100001 01110011 00000000 00000000 00000000
00000000 00000000 00000000 00000000 00011110 00000000 00000000 00000000
01101101 01101001 01110010 01111001 01100001 01101101 00000000 00000000
00000000 00000000 00000000 00000000 00101000 00000000 00000000 00000000
00100101
So here on the binary file the first 10 bytes should have been the ones that contain the contents of newStudent[0].name that is joseph and the next 4 bytes after the first 10 should contain the contents of newStudent[0].age that is the number 20 right? but thats not the case here, C++ actually gave the strings 12 bytes each instead of 10 bytes, making the size of students 16 bytes in total instead of 14 bytes why is that?