x

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:

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
  • 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.

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

Continue on C – Structure Padding….

Continue on C – Dynamic memory allocation in C….

Prev     Next



Like it? Please Spread the word!