Re: sizeof error?
- From: "Nikolaos D. Bougalis" <nikb@xxxxxxxxxxxxx>
- Date: Tue, 09 Aug 2005 22:44:06 -0700
Michael R. Copeland wrote:
> The following code compiles and executes, but it produces incorrect
> results (on VC++6.0), asfaics. The sizeof function that reference both
> the structure (T1) and the declared variable (t) yield 8, whereas the
> components of the structure add up to 6 (2 + 4). Can any explain
> why...or what can be done to make it work? TIA
>
> int main(int argc, char* argv[])
> {
> struct T1
> {
> int int_val;
> short short_val;
> } t = {0};
>
> size_t t1 = sizeof(int); // yields 4
> size_t t2 = sizeof(short); // " 2
> size_t t3 = sizeof(t); // " 8!
> size_t t4 = sizeof(T1); // " 8!!
>
> return 0;
> }
>
The compiler "pads" the structure to align it to memory boundaries. In
this case, it adds an extra two bytes to it, to bring it to a total of 8
instead of 6.
You can use #pragma pack to change the alignment on a
per-structure-definition basis, or /Zp<num> to the compiler to do it on
a project wide basis.
However, you should not mess with that, unless you have a very good
reason to (such as trying to "mirror" a hardware-based data structure in
software), because it can negatively affect performance.
-n
.
- Follow-Ups:
- Re: sizeof error?
- From: Michael R. Copeland
- Re: sizeof error?
- References:
- sizeof error?
- From: Michael R. Copeland
- sizeof error?
- Prev by Date: sizeof error?
- Next by Date: Re: sizeof error?
- Previous by thread: sizeof error?
- Next by thread: Re: sizeof error?
- Index(es):