面试题目--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

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

猜你喜欢

转载自blog.csdn.net/Doutd_y/article/details/81902643