如何计算的sizeof结构的大小

如何计算的sizeof结构的大小

本文介绍了如何计算的sizeof结构的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道一个char和int被计算为8个字节,由于对准32位架构,但我最近碰到一种情况,有3个短裤的结构被报告为6个字节的sizeof操作符。 code是如下:

I know that a char and an int are calculated as being 8 bytes on 32 bit architectures due to alignment, but I recently came across a situation where a structure with 3 shorts was reported as being 6 bytes by the sizeof operator. Code is as follows:

#include <iostream>
using namespace std ;

struct IntAndChar
{
    int a ;
    unsigned char b ;
};


struct ThreeShorts
{
    unsigned short a ;
    unsigned short b ;
    unsigned short c ;
};


int main()
{
    cout<<sizeof(IntAndChar)<<endl; // outputs '8'
    cout<<sizeof(ThreeShorts)<<endl; // outputs '6', I expected this to be '8'
    return 0 ;
}

编译器:G ++(Debian的4.3.2-1.1)4.3.2。这真让我为难,为什么不强制对齐含有3短裤结构?

Compiler : g++ (Debian 4.3.2-1.1) 4.3.2. This really puzzles me, why isn't alignment enforced for the structure containing 3 shorts?

推荐答案

这是因为 INT 4个字节,并且必须对齐到4字节的边界。这意味着任何结构包含 INT 也必须对齐到至少4个字节。

That's because int is 4 bytes, and has to be aligned to a 4-bytes boundary. This means that ANY struct containing an int also has to be aligned to at least 4-bytes.

在另一方面,是2字节,并且需要对准仅到2个字节的边界。如果结构包含 s不包含任何需要一个较大的调整,在结构也将被排列为2个字节。

On the other hand, short is 2 bytes, and needs alignment only to a 2-bytes boundary. If a struct containing shorts does not contain anything that needs a larger alignment, the struct will also be aligned to 2-bytes.

这篇关于如何计算的sizeof结构的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 00:15