struct 成员如何在内存中分配? [英] How are struct members allocated in memory?

查看:26
本文介绍了struct 成员如何在内存中分配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

While attempting to create a memory manager for future C programs, I've come across this question:

例如,考虑以下结构.

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

分配时,字段的内存地址会按照field1、field2、field3的顺序排列吗?还是不能保证?

When allocated, will the memory addresses of the fields be in the order field1, field2, field3? Or is this not guaranteed?

推荐答案

简短回答:它们按照它们在结构中声明的顺序进行分配.

Short answer: they are allocated with the order as they declared in the struct.

示例:

#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
", 
        sizeof(record1));

    printf("
Address of id1        = %u", &record1.id1 );
    printf("
Address of id2        = %u", &record1.id2 );
    printf("
Address of a          = %u", &record1.a );
    printf("
Address of b          = %u", &record1.b );
    printf("
Address 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 中的内存分配概念.

The pictorial representation of above structure memory allocation is given below. This diagram will help you to understand the memory allocation concept in C very easily.

进一步阅读:查看此处(也是上述示例的源代码)用于C – Structure PaddingC 中的结构动态内存分配.

Further reading: check out here (also the source for the above example) for C – Structure Padding and Structure dynamic memory allocation in C.

这篇关于struct 成员如何在内存中分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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