EmbLogic's Blog

C – Struct memory allocation

Do you know how memory is allocated for structure members in C

Always, contiguous(adjacent) memory locations are used to store structure members in memory. Consider below example to understand how memory is allocated for structures.

Example program for memory allocation in C structure

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

 Output:

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

           There are 5 members declared for structure in above program. In 32 bit compiler, 4 bytes of memory is occupied by int datatype. 1 byte of memory is occupied by char datatype and 4 bytes of memory is occupied by float datatype.

Please refer below table to know from where to where memory is allocated for each datatype in contiguous (adjacent) location in memory.

Datatype Memory allocation in C (32 bit compiler)
From Address To Address Total bytes         
int id1 675376768 675376771 4
int id2 675376772 675376775 4
char a 675376776 1
char b 675376777 1
Addresses 675376778 and 675376779 are left empty
(Do you know why? Please see Structure padding topic below)
2
float percentage 675376780 675376783 4

           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 members storage in memory

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>