web analytics

Understanding the Size of a Structure in C and C++

Options

davegate 143 - 921
@2015-12-19 13:03:06

Don't assume that the size of a structure is the sum of the sizes of its members. Because of alignment requirements for different objects, there may be unnamed "holes'' in a structure.

Thus, for instance, if a char is one byte and an int four bytes, the structure

struct

{
   char c;
   int i;
};

might well require eight bytes, not five. The sizeof operator returns the proper value.

@2015-12-23 13:10:38

Run the following C++ code to show you the result.

struct MyStruct
{
    char c;
    int i;
};

 

int main()
{
   MyStruct ms;
   std::cout << "size of MyStruct: " << sizeof ms << '\n';
   cin.get();
}

output

size of MyStruct: 8
@2015-12-23 22:15:19

When sizeof is applied to an empty class type, the result is always 1.

When sizeof is applied to a class type, the result is the size of an object of that class plus any additional padding required to place such object in an array.

When sizeof is applied to an expression that designates a polymorphic object, the result is the size of the static type of the expression.

 

Run the following C++ code to see above result.

#include <iostream>

using namespace std;

struct Empty {};

struct Base { int a; };

struct Derived : Base { char b; };

int main()

{

   Empty e;

   Derived d;

   Base& b = d;

   std::cout << "size of empty class: " << sizeof e << '\n'

             << "size of the Derived: " << sizeof d << '\n'

             << "size of the Derived through Base: " << sizeof b << '\n';

   cin.get();

}

output:

 

Comments

You must Sign In to comment on this topic.


© 2024 Digcode.com