为什么此结构定义会增加额外的一个字节的内存使用量? [英] Why does this struct definition add extra one byte of memory usage?

查看:63
本文介绍了为什么此结构定义会增加额外的一个字节的内存使用量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <stdio.h>
typedef struct {
    short x,y;
    char type;
} Tile;

int main(int argc, const char *argv[])
{
    printf("%d\n",sizeof(short));
    printf("%d\n",sizeof(char));
    printf("%d\n",sizeof(Tile));
    return 0;
}

输出为:

2
1
6

我希望sizeof(Tile)是5,而不是6.这是否是一种结构良好的行为,该结构会增加一个额外的字节内存使用量,还是依赖于实现?

I expected sizeof(Tile) to be 5, instead of 6. Is this a well-defined behaviour that structs add one extra byte of memory usage, or is it implementation dependant?

推荐答案

这是因为填充(有点像舍入).

It's because of padding (kind of like rounding).

例如:

struct example1
{
    char a;
    int b;
    char c;
}

struct example2
{
    char a;
    char b;
    int c;
}

大小可能会有所不同,第一个将为12B,第二个可能仅吃8B(取决于arch和编译器).

will likely differ in size, first will have size of 12B, second will likely only eat 8B (arch and compiler dependant).

gcc会根据结构最大成员的大小进行填充.

gcc does padding by size of biggest memeber of struct.

Gcc可以通过选项-fpack-struct最小化此行为,但这可能不是最好的主意,甚至可能适得其反(网络协议实现是我想到的第一件事).

Gcc can minimize this behavior by option -fpack-struct, however this may not be best idea ever, it could even backfire (network protocol implementantion is first thing that pops into my mind).

这篇关于为什么此结构定义会增加额外的一个字节的内存使用量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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