ADVERTISEMENT
ADVERTISEMENT

Home » Code Snippets » C/C++ Code Snippets

C program to determine the size of the structure and why the size of structure is different from all member’s occupied size?

By: IncludeHelp On 11 DEC 2016

Here, we will learn how to determine the size of the structure and why the size of structure is different from all member’s occupied size?

ADVERTISEMENT

How to get size of the structure?

We can get the size of any structure or other kind of variables by using sizeof operator.

There are two ways to get the size of structure

  • By using structure name
  • By using structure variable name

Let’s consider the example first

#include <stdio.h>

struct temp
{
	char a;
	int b;
	float c;
};

int main()
{
	struct temp objTemp;
	printf("Size of structure temp is: %d\n",sizeof(objTemp));
	printf("Size occupied by a: %d\n",sizeof(objTemp.a));
	printf("Size occupied by b: %d\n",sizeof(objTemp.b));
	printf("Size occupied by c: %d\n",sizeof(objTemp.c));
	return 0;
}

Output

    Size of structure temp is: 12 
    Size occupied by a: 1 
    Size occupied by b: 4 
    Size occupied by c: 4

Why the size of structure is different from the sum of occupied size of all members?

To match the alignment constraints extra bytes adds in the whole size of the structure. This is done by structure padding [to match the alignment constraints one or more empty bytes inserted between the allocated size of structure members known as structure padding].


COMMENTS

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.