设为首页 加入收藏

TOP

C++结构体占内存大小的判断(一)
2013-01-25 17:52:02 来源: 作者: 【 】 浏览:1170
Tags:结构 内存 大小 判断
  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;
}

  代码三的运行结果如下图所示:

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

   

首页 上一页 1 2 3 下一页 尾页 1/3/3
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Qt正则表达式的贪婪模式 下一篇表达式和基本语句

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: