1、功能: 申明一个结构体,在以下四种情况下判断其占有的内存空间的大小;
2、程序及其代码
2.1 最大化对其原则
代码一:结构体中不包含字符串变量的时候;
// 结构体占内存空间的判断.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include "String.h" #include "iostream" using namespace std; int _tmain(int argc, _TCHAR* argv[]) { typedef struct STUDENT_INFO { char num; int age; float salary; //string name; }*LP_STUDENT_INFO; cout<<sizeof(STUDENT_INFO)<<endl; /*string stuName; cout<<sizeof(stuName)<<endl;*/ return 0; } |
代码一的输出结果如下图:

可以看出其分配内存空间的规则是按照结构体变量中占内存字节最大大变量统一规划,因为float占有四个B,故三个变量攻占有12B;
2.2 字符串变量单算原则
代码二:当含有字符串变量时;
// 结构体占内存空间的判断.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include "String.h" #include "iostream" using namespace std; int _tmain(int argc, _TCHAR* argv[]) { typedef struct STUDENT_INFO { char num; int age; float salary; string name; }*LP_STUDENT_INFO; cout<<"申明的结构体占有的内存空间大小为:"<<sizeof(STUDENT_INFO)<<"B字节"<<endl; string stuName; cout<<"字符串变量占有的固定内存空间大小为:"<<sizeof(stuName)<<"B字节"<<endl; return 0; } |
代码二运行的结果如下图所示: 
说明其是在一原有的规则上面字符串变量单独计算;
如下面代码三:
// 结构体占内存空间的判断.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include "String.h" #include "iostream" using namespace std; int _tmain(int argc, _TCHAR* argv[]) { typedef struct STUDENT_INFO { char num; int age; float salary; string name; string name1;//相对于代码二此处又多定义一个字符串变量 }*LP_STUDENT_INFO; cout<<"申明的结构体占有的内存空间大小为:"<<sizeof(STUDENT_INFO)<<"B字节"<<endl; string stuName; cout<<"字符串变量占有的固定内存空间大小为:"<<sizeof(stuName)<<"B字节"<<endl; return 0; } |
代码三的运行结果如下图所示:

注意结构体中的变量在申明的时候不可以被初始化;