zoukankan      html  css  js  c++  java
  • 内存对齐规则

    1. 结构体(struct)/联合体(union)里的数据成员:第一个数据成员放在offset为0的地方,以后每个数据成员存储的起始位置要从该成员大小的整数倍开始。
    2. 结构体作为成员:如果一个结构里有某些结构体成员,则结构体成员要从其内部最大元素大小的整数倍地址开始存储。
    3. 结构体的总大小对齐:也就是sizeof的结果,必须是其内部最大成员的整数倍,不足的要补齐。
    VS2013 + WIN7_64
    char = 1
    short = 2
    int = 4
    long = 4
    float = 4
    double = 8


    实例:
    #include <iostream>
    using namespace std;
    
    typedef struct StuInfo
    {
    	int id;//4个字节,0 - 3
    	double weight;//8个字节,8 - 15
    	float height;//4个字节,16 - 19
    	//整体对齐4 * 5 = 20
    }StuInfo;
    
    typedef struct Stu
    {
    	char name[2];//2个字节,0 - 1
    	int id;//4个字节,4 - 7
    	double score;//8个字节,8 - 15
    	short grade;//2个字节,16 - 17
    	StuInfo c;//24个字节,24 - 47
    }Stu;
    
    int main(void)
    {
    
    	cout << "StuInfo = " << sizeof(StuInfo) << endl;
    	cout << "Stu = " << sizeof(Stu) << endl;
    	
    	
    	/*
    	cout << "char = " << sizeof(char) << endl;
    	cout << "short = " << sizeof(short) << endl;
    	cout << "int = " << sizeof(int) << endl;
    	cout << "long = " << sizeof(long) << endl;
    	cout << "float = " << sizeof(float) << endl;
    	cout << "double = " << sizeof(double) << endl;
    	*/
    	return 0;
    }


    输出:
    StuInfo = 24
    Stu = 48

    --------------------------------------------------------------------------------------------------
    当我们在VS设置#pragma pack(1)时,是在告诉编译器,所有的对齐都是按照1的整数倍,即不采用内存对齐规则。所以以上输出为:
    StuInfo = 16
    Stu = 32

    #pragma pack(4) ---->所有的对齐都是按照4的整数倍

    #pragma pack(4)
    #include <iostream>
    using namespace std;
    
    typedef struct StuInfo
    {
    	int id;//4个字节,0 - 3
    	double weight;//8个字节,4 - 11
    	float height;//4个字节,12 - 15
    }StuInfo;//16个字节
    
    typedef struct Stu
    {
    	char name[2];//2个字节,0 - 1
    	int id;//4个字节,4 - 7
    	double score;//8个字节,8 - 15
    	short grade;//2个字节,16 - 17
    	StuInfo c;//16个字节,20 - 35
    }Stu;//36个字节
    
    int main(void)
    {
    
    	cout << "StuInfo = " << sizeof(StuInfo) << endl;
    	cout << "Stu = " << sizeof(Stu) << endl;
    	
    	
    	/*
    	cout << "char = " << sizeof(char) << endl;
    	cout << "short = " << sizeof(short) << endl;
    	cout << "int = " << sizeof(int) << endl;
    	cout << "long = " << sizeof(long) << endl;
    	cout << "float = " << sizeof(float) << endl;
    	cout << "double = " << sizeof(double) << endl;
    	*/
    	return 0;
    }
    输出:
    StuInfo = 16
    Stu = 36




    Keep it simple!
    作者:N3verL4nd
    知识共享,欢迎转载。
  • 相关阅读:
    【转】虚函数什么情况下会内联
    构造函数不能为虚函数的原因
    《python编程》第四章——文件和目录工具
    《python编程》第三章笔记——脚本运行上下文
    《python编程》第二章笔记
    《Python编程》第一章笔记
    报错:IndentationError:unindent does not match any outer indentation level
    报错:SyntaxError: Non-ASCII character 'xe7' in file:
    1-2、make_db_file.py
    1-1.initdata.py
  • 原文地址:https://www.cnblogs.com/lgh1992314/p/6616350.html
Copyright © 2011-2022 走看看