C++中结构体占内存空间大小的判断
作者:网络转载 发布时间:[ 2013/1/22 10:09:26 ] 推荐标签:
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;
}

sales@spasvo.com