The Structure is defined as follows
typedef struct Sample
{
int test;
char strtest;
} Sample;
In Main Function, I called Sizeof the structure.
sizeof(struct Sample)
I've heard the return value of sizeof on structures could be incorrect. If this is the case, what should I do to get the right value?
The sizeof for a struct is not always equal to the sum of sizeof of each individual member. This is because of the padding added by the compiler to avoid alignment issues. Padding is only added when a structure member is followed by a member with a larger size or at the end of the structure.
It returns the size of a variable. It can be applied to any data type, float type, pointer type variables. When sizeof() is used with the data types, it simply returns the amount of memory allocated to that data type.
The sizeof() function in C is a built-in function that is used to calculate the size (in bytes)that a data type occupies in the computer's memory. A computer's memory is a collection of byte-addressable chunks.
It does return a reliable value - just not always the value you expect.
In Sample structure, you are assuming a 1 byte char and 4 byte int, but you do not get a result of "5" .
Because the structure is padded so that elements start on their natural boundaries. you are more likely to get a result of "8".
Wiki explains this pretty well: http://en.wikipedia.org/wiki/Sizeof - at "Structure Padding", near the bottom.
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