I know that the size of a structure is known at compile time, so it should be possible to find the size of a structure during programming. How can I do this?
To be more specific:
I have a structure say:
struct mystruct
{
int a;
char b;
float c[100];
}
I can write this line in my code and run application and see the size of this structure:
int size=sizeof(mystruct);
cout<<"size is="<<size<<endl;
But this involves adding a bit of code to my application and running it.
Is there any way that Visual Studio IDE can help me to find what is the size of this structure (for example by putting my cursor on it and pressing a key!)
In C language, sizeof() operator is used to calculate the size of structure, variables, pointers or data types, data types could be pre-defined or user-defined. Using the sizeof() operator we can calculate the size of the structure straightforward to pass it as a parameter.
The size of a structure is greater than the sum of its parts because of what is called packing. A particular processor has a preferred data size that it works with. Most modern processors' preferred size if 32-bits (4 bytes).
For 'int' and 'double', it takes up 4 and 8 bytes respectively. The compiler used the 3 wasted bytes (marked in red) to pad the structure so that all the other members are byte aligned. Now, the size of the structure is 4 + 1 +3 = 8 bytes. The size of the entire structure is 8 bytes.
We assume that the size of the int is 4 bytes, and the size of the char is 1 byte. In the above case, when we calculate the size of the struct student, size comes to be 6 bytes.
Given a type T, write the following:
constexpr size_t sizeOfT = sizeof(T);
Mouse over sizeOfT
, and you'll see the size of the struct as the value of this constexpr.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With