1、概述
#pragma pack(n)
作用是用于设置内存对齐方式,n可以为1,2,4等,如下面代码所示:
2、代码示例
#include "stdafx.h"
#include <Windows.h>
#include <iostream>
#pragma pack(1)
struct
{
char a;
WORD b;
DWORD c;
char d;
WORD e;
} st_demo1;
#pragma pack()
struct
{
char a;
WORD b;
DWORD c;
char d;
WORD e;
} st_demo2;
#pragma pack(2)
struct
{
char a;
WORD b;
DWORD c;
char d;
WORD e;
} st_demo3;
#pragma pack()
#pragma pack(4)
struct
{
char a;
WORD b;
DWORD c;
char d;
WORD e;
} st_demo4;
#pragma pack()
int _tmain(int argc, _TCHAR* argv[])
{
int len1 = sizeof(st_demo1);
std::cout << "sizeof(st_demo1) is:" << len1 << "\n";
int len2 = sizeof(st_demo2);
std::cout << "sizeof(st_demo2) is:" << len2 << "\n";
int len3 = sizeof(st_demo3);
std::cout << "sizeof(st_demo3) is:" << len3 << "\n";
int len4 = sizeof(st_demo4);
std::cout << "sizeof(st_demo4) is:" << len4 << "\n";
system("pause");
return 0;
}
3、结果示例
sizeof(st_demo1) is:10
sizeof(st_demo2) is:12
sizeof(st_demo3) is:12
sizeof(st_demo4) is:12
请按任意键继续. . .
4、结论
(1)在编码集在unicode的情况下,设置n为2、4或默认情况下,所得长度一致;
(2)在n为1的情况下,以一个字节为单位存放数据;虽然节省空间,但是操作系统任然要进行转化,会有一定的效率损失;