As you can see, both arrays are of equal size.
Actually, both structs might be the same size but that will depend on the way the compiler packs the structures: see Data Structure Alignment. You will probably get away with it most of the time if all the elements are chars. If you mix types then watch out:
#include <iostream>
struct myFirstStruct
{
unsigned char c1;
unsigned char c2;
unsigned char c3;
unsigned char c4;
unsigned char c5;
unsigned char carray1[6];
};
struct mySecondStruct
{
unsigned char carray1[4]; // 4*1 byte
unsigned char c1;
unsigned char carray2[6];
};
struct myThirdStruct
{
unsigned short sarray1[2]; // 2*2 bytes
unsigned char c1;
unsigned char carray2[6];
};
int main(int argc, char **argv)
{
std::cout << sizeof(unsigned char) << " " << sizeof(unsigned short) << std::endl;
std::cout << sizeof(myFirstStruct) << " " << sizeof(mySecondStruct) << " " << sizeof(myThirdStruct) << std::endl;
return 0;
}
#include <iostream>
struct myFirstStruct
{
unsigned char c1;
unsigned char c2;
unsigned char c3;
unsigned char c4;
unsigned char c5;
unsigned char carray1[6];
};
struct mySecondStruct
{
unsigned char carray1[4]; // 4*1 byte
unsigned char c1;
unsigned char carray2[6];
};
struct myThirdStruct
{
unsigned short sarray1[2]; // 2*2 bytes
unsigned char c1;
unsigned char carray2[6];
};
int main(int argc, char **argv)
{
std::cout << sizeof(unsigned char) << " " << sizeof(unsigned short) << std::endl;
std::cout << sizeof(myFirstStruct) << " " << sizeof(mySecondStruct) << " " << sizeof(myThirdStruct) << std::endl;
return 0;
}
To copy to clipboard, switch view to plain text mode
outputs:
1 2
11 11 12
1 2
11 11 12
To copy to clipboard, switch view to plain text mode
To do this cast safely requires an explicit copy constructor.
Bookmarks