sizeof().cpp - 一目了然

//sizeof().cpp
//关于sizeof对基本数据类型、结构体、类、STL容器的用法均以C++代码和注释给出

//在VC 6.0上编译通过,可复制文章直接运行,希望有帮助^_^

#include <iostream>
#include <vector>
#include <string>
using namespace std;

 

struct S1 { //sizeof(S1)==8
 short a; //2
 short b; //2
 int c; //4
};

 

struct S2 { //sizeof(S2)==12
 short a; //2+2( 字节对齐为2(方便计算机进行存取操作)
               //从而凑足结构体中的最宽元素(此处为int——4个字节),参见下例S3 )
 int b; //4
 short c; //2+2
};


struct S3 { //sizeof(S2)==24
 short a; //2
 int b; //4+2
 double c; //8
 short d; //2+6
};

 

class C { //sizeof(C)==2
 short a;
};

 

int main()
{
 cout<<sizeof(S1)<<endl;
 cout<<sizeof(S2)<<endl;
 cout<<sizeof(S3)<<endl;
 cout<<endl;
 
 S1* s;
 cout<<sizeof(s)<<endl; //指针变量总是返回4
 cout<<endl;

 

 double* a=new double[8]; //堆上分配内存
 cout<<sizeof(a)<<endl; //sizeof(ptr)==4
 cout<<sizeof(*a)<<endl; //sizeof(double)==8
 cout<<endl;

 

 char* ss;
 cout<<sizeof(ss)<<endl; //sizeof(ptr)==4
 cout<<sizeof(*ss)<<endl; //sizeof(char)==1
 cout<<endl;


 //我们可以得出结论,内存分配对结构体(或类)和普通变量(如int)是不公平对待的
 //当然运气好的时候结果会一致,比如:
 C c;
 short cc;
 cout<<sizeof(c)<<" "<<sizeof(cc)<<endl; //sizeof(C)==sizeof(short)==2
 cout<<endl;
 
 //sizeof()在编译时起作用(栈内),而不是运行时
 //而vector的元素是动态分配的(堆上分配内存),因此sizeof(vector<int>)总是返回16
 //16便是vector类的非静态数据成员所占用的空间,如下:
 //_A allocator; iterator _First,_Last,_End;
 vector<int> v(999);
 cout<<sizeof(v)<<" "<<sizeof(vector<int>)<<endl;
 cout<<sizeof(string)<<endl; //同样地,sizeof(string)==16

 cout<<endl;


 return 0;

}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值