关于内存字节大小的测试,用sizeof();

各个变量在 计算内存中占有的字节大小为多少,最近由于学算法,然后进行了简单的测试。

sizeof()函数:返回对象或者类型所占的字节数,其返回值类型为size_t,在头文件stddef.h中定义。

测试代码(C++):

#include 

using namespace std;

int main(){
        cout    << "the byte of char is :  "<< sizeof(char)<<"\n"
                << "the byte of int is :  "<< sizeof(int)<<"\n"
                << "the byte of unsigned is :  "<< sizeof(unsigned)<<"\n"
                << "the byte of double is :  "<< sizeof(double)<<"\n"
                << "the byte of long double is :  "<< sizeof(long double)<<"\n"
                << "the byte of float is :  "<< sizeof(float)
                <

测试结果如下:

the byte of char is :  1
the byte of int is :  4
the byte of unsigned is :  4
the byte of double is :  8
the byte of long double is :  16
the byte of float is :  4

 此代码亦可以用C来写,直接用printf函数,如下

	printf("the byte of int/unsigned/double/long double/float is \t%d\t%d\t%d\t%d\t%d\n",sizeof(int),sizeof(unsigned),sizeof(long),sizeof(long double),sizeof(float));

附注:

1、计算机上的所有数据都是以“位”(bit)来存储的,1bit就代表一个0或1;

2、字节(byte):8bit=1byte,一个英文字母占一个字节,一个汉字占用两个字节。一般情况下,bit用小写“b”表示,byte用大写“B”表示。

3、1KB=1024B ,1MB=1024KB,1G=1024MB。

4、1万汉字的小说,要用多少内存才能存储?10万汉字*2B=200'000B=195.3KB=0.19MB,如果仅仅简单估算的话,假定1KB=1000B,那么10万汉字占用的内存就是200KB,约0.2MB。

5、一般的网络速度衡量单位都是“位每秒”(bps)。


 



你可能感兴趣的:(C++学习日记)