Structure storage in memory
The members of a structure are stored consecutively in the memory. The size of members may differ from one machine to machine. But the important point to note about member storages is, they are stored consecutively in memory.
Example program to understand structure member storage
In the below example, there is a structure named stu and it has members: c, C, f, F, i. Addresses of all members are printed at the output. s1 is a variable of structure stu.
Here %u is used to print the address of any variable. As observed in the output, all members are stored line by line, meaning one after one in sequence. So we can say that members c, C, f, F, I are stored consecutively in memory.
#include <stdio.h> #include <conio.h> struct stu{ char c,C; float f,F; int i; }s1; void main() { clrscr(); printf("address of c : %u \n",&s1.c); printf("address of C : %u \n",&s1.C); printf("address of f : %u \n",&s1.f); printf("address of F : %u \n",&s1.F); printf("address of i : %u \n",&s1.i); getch(); }
Output:
Size of structure
Size of structure is the addition of size of its all members. As said earlier, the size of members may differ from machine to machine. To print the size of a structure (or any variable or any data type) we can use sizeof operator.
Example program to understand structure size
In the below program, the structure stu has 5 members: c, C, f, F, i. s1 is a variable of structure stu. Here size of structure is = size of c(1 byte) + size of C(1 byte) + size of f(4 bytes) + size of F(4 bytes) + size of i(2 bytes)= 12 bytes
#include <stdio.h> #include <conio.h> struct stu{ char c,C; float f,F; int i; }s1; void main() { clrscr(); //We are printing size of data type struct stu printf("%d \n",sizeof(struct stu)); //We are printing size of variable s1 printf("%d \n",sizeof(s1)); getch(); }
Output;
Learning from this blog:
- How is memory allocated for structure members?
- What do you mean by consecutive memory allocation?
- What is the size of any structure?
- Which operator is used to find the size of any variable?
- How to write code for memory allocation and size of structure?