Structure Padding Calculator

Structure Padding Calculator

Easy C Structures 36 views
Explanation Complexity

Problem Statement

Create a structure with char, int, char, or double members. Use sizeof() to find the total size. Then calculate it manually, taking into account padding. Why does the compiler add padding?

Input Format

A structure with members:

• char

• int

• char

• double

Output Format

Total size of structure using sizeof()
AND
Manual size calculation with padding.

Example

Structure members order:
char a; int b; char c; double d;
Size using sizeof() = 24 bytes

Constraints

• Compiler uses padding

• Memory alignment rules apply

Concept Explanation

Compiler adds padding bytes to align data properly in memory.

Step-by-Step Explanation

1.char a → 1 byte

2.Next is int b (needs 4-byte alignment):

• Compiler adds 3 padding bytes after char a

• int b → 4 bytes

3.char c → 1 byte

4.Next is double d (needs 8-byte alignment):

• Compiler adds 7 padding bytes after char c

• double d → 8 bytes

5.Total calculation:

• 1 (char)

• + 3 (padding)

• + 4 (int)

• + 1 (char)

• + 7 (padding)

• + 8 (double)
= 24 bytes

Concept Explanation

Compiler adds padding bytes to align data properly in memory.

Step-by-Step Explanation

1.char a → 1 byte

2.Next is int b (needs 4-byte alignment):

• Compiler adds 3 padding bytes after char a

• int b → 4 bytes

3.char c → 1 byte

4.Next is double d (needs 8-byte alignment):

• Compiler adds 7 padding bytes after char c

• double d → 8 bytes

5.Total calculation:

• 1 (char)

• + 3 (padding)

• + 4 (int)

• + 1 (char)

• + 7 (padding)

• + 8 (double)
= 24 bytes

Input / Output Format

Input Format
A structure with members:

• char

• int

• char

• double
Output Format
Total size of structure using sizeof()
AND
Manual size calculation with padding.
Constraints
• Compiler uses padding

• Memory alignment rules apply

Examples

Input:
Structure members order: char a; int b; char c; double d;
Output:
Size using sizeof() = 24 bytes

Example Solution (Public)

C
#include <stdio.h>

struct Example {
    char a;     // 1 byte
    int b;      // 4 bytes
    char c;     // 1 byte
    double d;   // 8 bytes
};

int main() {
    printf("Size of structure = %lu bytesn", sizeof(struct Example));
    return 0;
}

Official Solution Code

#include <stdio.h>

struct Example {
    char a;     // 1 byte
    int b;      // 4 bytes
    char c;     // 1 byte
    double d;   // 8 bytes
};

int main() {
    printf("Size of structure = %lu bytesn", sizeof(struct Example));
    return 0;
}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.