What is padding in structure?
In C++, a structure is like a bookshelf with different shelves holding different kinds of books. Each shelf represents a piece of information, such as a number or a letter.
Now, picture the computer trying to arrange these shelves neatly in its memory, just like placing books on a bookshelf. However, there’s a rule: books should be put in specific spots, like every 4th spot or every 8th spot.
Padding in C++, it’s like arranging our bookshelves in a way that the computer can easily find and use the information, following its own set of rules. It’s similar to placing extra cushions on the bookshelf to make sure everything stays organized.
Let’s discuss the example of padding in programming.
Example of padding in struct
In C++, padding refers to the insertion of empty bytes between the members of a structure. The purpose of padding is to align the members in memory for more efficient access by the computer’s hardware.
Memory alignment
Computers often access memory more efficiently when data is aligned on certain byte boundaries (like
bytes or bytes). To achieve this alignment, the compiler may insert empty bytes (padding) between the members of a structure.
struct example
Imagine a structure with two members: an integer (
bytes) and a character ( byte). Without padding, the total size would be
bytes, but to align it on a -byte boundary, the compiler may insert bytes of padding after the character.
struct Example {int number; // 4 byteschar letter; // 1 byte}; // Total size: 8 bytes (including padding)
Let’s visualize the struct example mentioned above:
Let’s write down a complete code below and check the sizes of each member:
#include <iostream>using namespace std;struct Example {int number; // 4 byteschar letter; // 1 byte};int main() {// Print the size of the structurecout << "Size of Example structure: " << sizeof(Example) << " bytes" << std::endl;// Print the size of each member to analyze paddingcout << "Size of int: " << sizeof(int) << " bytes" << std::endl;cout << "Size of char: " << sizeof(char) << " bytes" << std::endl;return 0;}
Code explanation
Line 4–8: We define a structure named
Examplewith two members: an integernumber(bytes) and a character letter(byte). Line 11: We print the size of the structure (
bytes). The compiler will fill bytes of padding. Line 14–15: We print the size of each member to analyze the padding.
Free Resources