Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
458 views
in Technique[技术] by (71.8m points)

c - How are struct members allocated in memory?

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

"when structs are allocated, are their member fields stored in the order specified?"

For instance, consider the following struct.

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


Example:

#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;
}

Output:

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

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.

enter image description here


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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...