面试题目--sizeof

1、内建数据类型的大小

int intValue=1024;
int a[4][4];
int *b[4];
int c[10];

char str[]="bubuday";
char *sp = "bubuday";
const char* ch=str;
double *dp;

cout << sizeof(intValue) << endl;
cout << sizeof(a) << endl;
cout << sizeof(b) << endl;
cout << sizeof(c) << endl;

cout << sizeof(str) << endl;
cout << sizeof(sp) << endl;

cout << sizeof(ch) << endl;
cout << sizeof(dp) << endl;

输出为4,64,16,40,8,4,4,4。

对于32位的系统,分配给int

 2、结构体或类数据类型的大小

结构体1:

struct Student
{
    char name;
    short age;
    int height;
};

Student stu;

cout << sizeof(Student) << endl; // cout << sizeof(stu) << endl;

输出均为 8。在32位操作系统中,char 占1个字节,short 占2个字节,int 占4个字节,但由于字节对齐的原因,结构体Student所占的空间大小为 4+2+1+1(补齐) = 8。

 

结构体2:

typedef struct
{
    char a : 3;
    char b : 4;
    char c : 5;
    char d : 6;
    char e : 7;
}test1;

typedef struct
{
    char a : 3;
    char b : 6;
    char c : 5;
    char d : 4;
    char e : 2;
    char f : 4;
	
}test2;

cout << sizeof(test1) << endl;
cout << sizeof(test2) << endl;

输出为4(Byte)和5(Byte):

解释下内存分配,4Byte:1Byte(3bit,4bit,1bit填充)2Byte(5bit,3bit填充)3Byte(6bit,2bit填充)4Byte(7bit,1bit填充)

                             5Byte:1Byte(3bit,5bit填充)2Byte(6bit,2bit填充)3Byte(5bit,3bit填充)4Byte(4bit,2bit,2bit填充)5Byte(4bit,4bit填充)

char a:3 ;

char b:4;
char类型的size是8位,一个字节大小,或依据编译器内定。
char a : 3; //意思是指char类型变量a只使用低三位表示,即其取值范围是0x00~0x07
char b : 4; //意思雷同,b的取值可以是ox00~0xFF

对于结构体或类,成员变量的声明顺序不同会影响到该结构体数据类型所占空间的大小,且跟本地的编译器也有关。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值