结构体的字节数
sizeof()运算符用于计算基本类型、结构体类型的所占字节数;
#include <iostream>
using namespace std;
struct student{
int id;
char ch;
};
int main()
{
printf("%d\n",sizeof(int));
printf("%d\n",sizeof(char));
printf("%d",sizeof(student));
return 0;
}
对于基本数据类型,int一般占用4个字节,char一般占用1个字节。
代码中构造了一个student类型,包含一个int、一个char,但是运行程序会发现,结构体的字节数为8,而不是4+1=5,这是因为在内存中,数据是对齐存放的。
这个知识点,在408统考题中也会经常出现。数据对齐存放确实是浪费了一部分内存空间,但是,对于取指令和数据来书确实非常方便。