关于数据在内存中存储有点让我不解

来源:互联网 发布:ios宅男福利软件 编辑:程序博客网 时间:2024/05/07 12:01
#include <iostream>using namespace std;struct st{   char i;  int m;void prin(){  cout <<"this is hello"<<endl;}void prin2(){  cout <<"this is print2"<<endl;}};int main(){  cout << sizeof(st) <<endl;  cout <<"hello" <<endl;  struct st sti;  cout << sizeof sti <<endl;}

上面代码在GCC上进行编译运行结果(一):

8
hello
8
this is hello

如果去掉 int m; 运行结果(二)为:

1
hello
1
this is hello

如果去掉 char i; 则运行结果(三)为:

1
hello
1
this is hello

我有以下三个问题:

1、函数不占内存空间吗?

2、一个空的类,为什么还会占用一个字节的内存空间?

3、一个只有一个char 类型变量的类,为什么 sizeof 后还是一个字节 ?

希望高手指教


还有一些问题,也记下来吧,以后要看看STL源码,才能知道哦!

#include <stdio.h>#include <vector>#include <list>#include <map>#include <iostream>int main(){std::vector<int> test;std::list<int>li;std::map<int,double>m;std::cout << sizeof(test)<<std::endl<<  sizeof(li)<<std::endl<<  sizeof(m)<<std::endl;return 0;}


输出:

20
24
28
请按任意键继续. . .