结构因内存大小而异? [英] Struct varies in memory size?

查看:26
本文介绍了结构因内存大小而异?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么第一种情况不是 12?测试:最新版本的 gcc 和 clang,64 位 Linux

Why is not 12 in the first case? Tested on: latest versions of gcc and clang, 64bit Linux

struct desc
{
    int** parts;
    int nr;
};

sizeof(desc);输出:16

struct desc
{
    int** parts;
};

sizeof(desc);输出:8

struct desc
{
    int nr;
};

sizeof(desc);输出:4

推荐答案

允许编译器在 struct 成员之间添加填充以提高处理效率.此填充因平台、编译器版本等而异.这是无法通过网络发送 structs 的原因之一.

The compiler is allowed to add padding between struct members to make processing more efficient. This padding varies by platform, compiler version etc. It's one of the things that make sending structs over the network impossible.

您可以使用 offsetof 来找出编译器添加填充的确切位置.

You can use offsetof to find out where exactly your compiler is adding paddings.

这篇关于结构因内存大小而异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆