C中带有指针的结构的内存开销 [英] Memory overhead for structs with pointers in C

查看:59
本文介绍了C中带有指针的结构的内存开销的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我意识到当结构包含指针时,结构中会存在内存开销.这里有一个例子:

I realized there's a memory overhead in my structs when they contain a pointer. Here you have an example:

typedef struct {
    int num1;
    int num2;
} myStruct1;

typedef struct {
    int *p;
    int num2;
} myStruct2;

int main()
{
    printf("Sizes: int: %lu, int*: %lu, myStruct1: %lu, myStruct2: %lu\n", sizeof(int), 
        sizeof(int*), sizeof(myStruct1), sizeof(myStruct2));
    return 0;
}

这将在我的64位计算机上打印以下内容:

This prints the following in my 64-bit machine:

Sizes: int: 4, int*: 8, myStruct1: 8, myStruct2: 16

myStruct2的大小外,其他一切对我来说都很有意义,我认为它的大小仅为12,而不是16(sizeof(int*) + sizeof(int) = 12).

Everything makes sense to me except the size of myStruct2, which I thought it would only be 12 instead of 16 (sizeof(int*) + sizeof(int) = 12).

有人可以解释一下为什么会这样吗? 谢谢!

Could anyone explain me why this is happening? Thank you!

(我很确定这一定是在其他地方问过的,但我找不到它.)

(I'm pretty sure this must have been asked somewhere else, but I couldn't find it.)

推荐答案

即标准的 padding ,表示结构中或末尾(而不是开头)可能存在未命名的padding.草案C99标准部分6.7.2.1 结构和联合说明符段落 13 说:

That is padding the standard says there may be unnammed padding within a struct or at the end but not at the beginning. The draft C99 standard section 6.7.2.1 Structure and union specifiers paragraph 13 says:

[...]结构对象中可能存在未命名的填充,但在其开头没有.

[...]There may be unnamed padding within a structure object, but not at its beginning.

和第 15 段说:

结构或联合的末尾可能存在未命名的填充.

There may be unnamed padding at the end of a structure or union.

这篇关于C中带有指针的结构的内存开销的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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