C – Struct memory allocation

      Prev                                                                                               Next

           Do you know how memory is allocated for structure members in C?. You can learn below concepts of C in this topic.

    1. how structure members are stored in memory?
    2. What is structure padding?
    3. How to avoid structure padding?


1. How structure members are stored in memory?

           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 : %dn", 

    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

           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)
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

Continue on C – Structure Padding….

Continue on C – Dynamic memory allocation in C….

      Prev                                                                                               Next