带指针的结构的大小
size of Struct with pointer
我编译了这段代码:
// Example program
#include <iostream>
using namespace std;
struct A
{
char a;
};
struct B
{
char b;
int a;
};
struct C
{
int * a;
unsigned char b;
};
int main()
{
cout<< "size of Strcut A:\t"<< sizeof(A)<<endl;
cout<< "size of Strcut B:\t"<< sizeof(B)<<endl;
cout<< "size of Strcut C:\t"<< sizeof(C)<<endl;
cout<< "size of int* : \t"<< sizeof(int*)<<endl;
return 0;
}
我得到了这个结果:
size of Strcut A: 1
size of Strcut B: 8
size of Strcut C: 16
size of int* : 8
现在我想问一下为什么Strcut B的大小不是5?为什么Struct C的大小不是9?
当内存在嵌入式系统中很重要时,我应该如何在其他平台(如 ARM)中节省内存?
我可以告诉编译器它是 5 个字节还是 9 个字节?
Alignment。数据结构的成员(及其总大小)之间用空 space 填充,以加快访问速度并减少当较大类型跨越边界时所需的冗余读取。
编译器决定添加一些额外的填充位来对齐您的结构。
使用 8 次幂的数据然后花时间从内存中提取它们要快得多。
我编译了这段代码:
// Example program
#include <iostream>
using namespace std;
struct A
{
char a;
};
struct B
{
char b;
int a;
};
struct C
{
int * a;
unsigned char b;
};
int main()
{
cout<< "size of Strcut A:\t"<< sizeof(A)<<endl;
cout<< "size of Strcut B:\t"<< sizeof(B)<<endl;
cout<< "size of Strcut C:\t"<< sizeof(C)<<endl;
cout<< "size of int* : \t"<< sizeof(int*)<<endl;
return 0;
}
我得到了这个结果:
size of Strcut A: 1
size of Strcut B: 8
size of Strcut C: 16
size of int* : 8
现在我想问一下为什么Strcut B的大小不是5?为什么Struct C的大小不是9? 当内存在嵌入式系统中很重要时,我应该如何在其他平台(如 ARM)中节省内存?
我可以告诉编译器它是 5 个字节还是 9 个字节?
Alignment。数据结构的成员(及其总大小)之间用空 space 填充,以加快访问速度并减少当较大类型跨越边界时所需的冗余读取。
编译器决定添加一些额外的填充位来对齐您的结构。 使用 8 次幂的数据然后花时间从内存中提取它们要快得多。