2

I want to know the reason of increasing the size of struct Player from 25 to 32 bytes. I know using #pragma pack(push,1) to strict padding and #pragma pack(pop) to release padding of struct but I want to know why even this behavior is occurred, what secrets are behind it?

#include <iostream>
#include <fstream>
using namespace std;

struct player
{
    char name [13];
    int age;
    double score;
};
int main()
{
    cout << sizeof(player) << '\n';
    return 0;
} 

OutPut: 32

Ali-Baba
  • 198
  • 1
  • 9
  • 4
    `int`: 4-byte allignment, add 3-byte padding before that `double`: 8-byte allignment, add 4-byte padding before that – MikeCAT Nov 14 '20 at 00:14
  • 3
    This padding is done to make the stroke more efficient to work with. – Саша Nov 14 '20 at 00:15
  • 1
    If you want to have a small yet computationally inefficient struct, look into `#pragma pack` – Rogue Nov 14 '20 at 00:17
  • 3
    You can also often get a smaller structure by arranging the variables in the structure to reduce the need for padding. – user4581301 Nov 14 '20 at 00:25
  • 1
    OT: Prefer to use `std::string` for text instead of character arrays. Character arrays can overflow or underflow. They can become exciting when there is no terminating nul character. – Thomas Matthews Nov 14 '20 at 00:47
  • 1
    Let's say your processor has 32-bit integers. It's defined to fetch 32-bits at a time. If the `int` is on a 32-bit aligned boundary, the processor only has to make one fetch. Any other boundary and the processor may need to make multiple fetches to build a 32-bit integer. Some processors can only access ints on 32-bit boundaries, otherwise they issue faults. – Thomas Matthews Nov 14 '20 at 00:50
  • 1
    [Why isn't sizeof for a struct equal to the sum of sizeof of each member?](https://stackoverflow.com/q/119123/995714) – phuclv Nov 14 '20 at 03:04
  • 1
    you should almost always arrange struct members from large to small to minimize the padding. You're doing the reverse thing in this case – phuclv Nov 14 '20 at 03:05

0 Answers0