Prev Next
Do you know how memory is allocated for structure members in C? You can learn below concepts of C in this topic.
- how structure members are stored in memory?
- What is structure padding?
- 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
#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 : 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.
- 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.
Continue on C – Structure Padding….
Continue on C – Dynamic memory allocation in C….