Here in this page, we will find out structure size in C++,
as mentioned earlier, we can find out the size of any data-type or variable from the sizeof operator.
The sizeof operator has also been used in the program given below.
To know the size of a structure, we first declare the structure-variable. The size of this structure-variable is the size of the structure itself.
Here is an example,
found out structure size using sizeof operator
#include<iostream>
using namespace std;
struct get_size
{
int a; // 2byte
float b; //4 byte
char c; //1 byte
} x;
void main()
{
cout<<"size of structure(in byte): "<<sizeof(x);
getch();
}
OUTPUT
size of structure(in byte): 7
Explanation
In the program, three types of data-member (int, float and char) of the structure test are declared and we know how much space they reserve in the data-type memory.
So here all the data-members total size
int + float + char = structure variable size
such as,
2 + 4 + 1 = 7 bytes
will be the size of the structure.
structure and class are similar in most cases so Found out a class-variable size will be the same as the above program.
Note
Related Exercise,
C++ Examples