在这一篇,咱们弄清楚一些常见变量类型在内存中的占用!
/*
-----------------------------------------------------------------------------
OS:Win10 x86_64
IDE:VS2012 Ultimate win32控制台
Author: Y. S. Cui
-----------------------------------------------------------------------------
*/
什么时候用 ?
- 首先,必须有这个意识:指针长度和地址总线有关。因为指针记录的就是一个地址,那么32位的就是4字节,64位的就是8字节。
#include <iostream> //#include <vector> using namespace std; int main() { double *p = nullptr; cout << " 变量类型 char 的大小为" << sizeof(char) << " Byte(s)" <<endl; cout << " 变量类型 short 的大小为" << sizeof(short) << " Byte(s)" <<endl; cout << " 变量类型 double的大小为" << sizeof(double) << " Byte(s)" <<endl; cout << " 变量类型 int 的大小为" << sizeof(int) << " Byte(s)" <<endl; cout << " 变量类型 float 的大小为" << sizeof(float) << " Byte(s)" <<endl; cout << " 变量类型 long int 的大小为" << sizeof(long int) << " Byte(s)" <<endl; cout << " 变量类型 long 的大小为" << sizeof(long) << " Byte(s)" <<endl; cout << " 变量类型 long long 的大小为" << sizeof(long long) << " Byte(s)" <<endl; cout << " 变量类型 unsigned long long 的大小为" << sizeof(unsigned long long) << " Byte(s)" <<endl; cout << " 指针char类型 的大小为" << sizeof(char *)<< " Byte(s)" <<endl; system("pause"); return 0; }
#include <iostream>
#include <string>
#define unsigned char unchar
#define unsigned int uint
using namespace std;
int main()
{
cout << " 类型名称 \t" << "大小" << endl;
cout << " bool \t" << sizeof(bool) << endl;
cout << " char \t" << sizeof(char) << endl;
cout << " wchar_t \t" << sizeof(wchar_t) << endl;
cout << " char16_t \t" << sizeof(char16_t) << endl;
cout << " char32_t \t" << sizeof(char32_t) << endl;
cout << " short \t" << sizeof(short) << endl;
cout << " int \t" << sizeof(int) << endl;
cout << " long \t" << sizeof(long) << endl;
cout << " long long \t" << sizeof(long long) << endl;
cout << " float \t" << sizeof(float) << endl;
cout << " double \t" << sizeof(double) << endl;
cout << " long double\t" << sizeof(long double) << endl;
system("pause");
return 0;
}