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?

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




Copyright © 2024 www.includehelp.com. All rights reserved.