consider the following snippet:
struct foo {
int a;
int b;
int c;
};
struct foo f;
printf("%u, %u\n", sizeof(struct foo), sizeof(f));
The code returns the same values, but I was wondering if sizeof() applied to variable is correct or this is just coincidence?
Thanks.
The sizeof operator is the most common operator in C. It is a compile-time unary operator and used to compute the size of its operand. It returns the size of a variable. It can be applied to any data type, float type, pointer type variables.
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.
In 32 bit processor, it can access 4 bytes at a time which means word size is 4 bytes. Similarly in a 64 bit processor, it can access 8 bytes at a time which means word size is 8 bytes.
The result of the sizeof operand applied to a structure object can be equal to the sum of sizeof applied to each member separately.
Both will and should indeed return the same value.
From MSDN:
The sizeof Operator
The sizeof operator gives the amount of storage, in bytes, required to store an object of the type of the operand. This operator allows you to avoid specifying machine-dependent data sizes in your programs.
sizeof unary-expression
sizeof ( type-name )
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