c++ - 带指针的结构的大小

标签 c++ struct sizeof

<分区>

我编译了这段代码:

// 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 个字节?

http://cpp.sh/2rv6b

最佳答案

Alignment .您的数据结构的成员(及其总大小)之间用空白填充,以加快访问速度并减少当较大类型跨越边界时所需的冗余读取。

关于c++ - 带指针的结构的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39134584/

相关文章:

c++ - OpenCL:clSetKernelArg 返回 CL_INVALID_ARG_SIZE

c++ - 为什么我的 C++ 输出可执行文件这么大?

c - C 结构中的松弛字节

c++ - 不做任何事情的结构的构造函数

c - C sizeof() 如何返回这些值

c - sizeof(函数名)

c# - 使用 memcpy 从 C++ 到 C#

c++ - 优化后的虚拟调用成本

struct - CUDA:在结构中分配结构数组

c++ - C/C++ 获取结构大小