如何在内存中分配结构成员?

问题描述 投票:13回答:3

[尝试为将来的C程序创建内存管理器时,我遇到了这个问题:

“分配结构时,其成员字段是否按指定顺序存储?”

例如,考虑以下结构。

typedef struct {
    int field1;
    int field2;
    char field3;
} SomeType;

[分配后,字段的存储地址是否按照字段1,字段2,字段3的顺序排列?还是不能保证?

c memory-management struct
3个回答
31
投票

简短回答:按照结构中声明的顺序分配它们。


示例

#include <stdio.h>
#include <string.h>

struct student 
{
    int id1;
    int id2;
    char a;
    char b;
    float percentage;
};

int main() 
{
    int i;
    struct student record1 = {1, 2, 'A', 'B', 90.5};

    printf("size of structure in bytes : %d\n", 
        sizeof(record1));

    printf("\nAddress of id1        = %u", &record1.id1 );
    printf("\nAddress of id2        = %u", &record1.id2 );
    printf("\nAddress of a          = %u", &record1.a );
    printf("\nAddress of b          = %u", &record1.b );
    printf("\nAddress of percentage = %u",&record1.percentage);

    return 0;
}

输出

size of structure in bytes : 16 
Address of id1 = 675376768
Address of id2 = 675376772
Address of a = 675376776
Address of b = 675376777
Address of percentage = 675376780

以下结构存储器分配的图形表示如下。此图将帮助您非常轻松地理解C语言中的内存分配概念。

<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS9ubU85My5wbmcifQ==” alt =“在此处输入图像说明”>“ >>


进一步阅读

:签出hereC – Structure PaddingStructure dynamic memory allocation in C(也是上面示例的来源)。

6
投票

[可以保证field3field2之后,在field1之后,并且field1在存储器的开头(即field1之前没有填充)。但是,它们可能在其他成员之间填充(甚至在field3之后)。简而言之,声明它们的顺序是它们在内存中的排列顺序,尽管实现了精确的对齐和填充(但在第一个成员之前不会有任何填充)。


0
投票
  1. 成员一一定位;
© www.soinside.com 2019 - 2024. All rights reserved.