20-09-2016, 10:55 AM
1455273517-ARTICLEONSTRUCTURESINCLANGUAGE11.docx (Size: 33.1 KB / Downloads: 5)
Structure is the collection of variables of different types under a single name for better handling
Ex:
Struct student
{
int id1,id2;
char a,b;
float percentage;
} record1;
Here record1 is a variable of student type, the size of record1 is 4+4+1+1+4=14 bytes(32 bit compiler int - 4 byte memory)
But in the following program the size of record1 variable is showing 16 bytes
Example program for memory allocation in C structure:
#include <stdio.h>
#include <string.h>
struct student
{
int id1,id1;
char a,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;
• In order to align the data in memory, one or more empty bytes (addresses) are left empty between memory addresses which are allocated for other structure members while memory allocation. This concept is called structure padding.
• Architecture of a computer processor is such a way that it can read 1 word (4 byte in 32 bit processor) from memory at a time.
• To make use of this advantage of processor, data are always aligned as 4 bytes package which leads to insert empty addresses between other member’s address.
• Because of this structure padding concept in C, size of the structure is always not same as what we think.
Id1 variable occupies 4 bytes memory i.e. memory address from 675376768 to 675376771,
Id2 variable occupies 4 bytes memory i.e. memory address from 675376772 to 675376775,
A, B character variables occupies 1 byte of memory each i.e. 675376776,675376777 respectively
Percentage- data type float requires whole 4 byte of memory in the package. But, this is not possible as only 2 bytes available in the package. So, next whole 4 byte package is used for structure member “percentage”. i.e. 675376780 to 675376783. So, size of structure is 16 bytes which is 2 bytes extra than what we think. Because, 2 bytes are left empty.