0
struct Node
{
    char        c;
    double      d;
    int         s;
} Node;

I recently started studying linked lists and in between just trying random things to explore. I tried getting size of the node at first i thought it would be 13 later on googling i found there is concept of padding and data alignment.

So My system has 64bit processor and according to that i calculated (1(char) + 7(for padding) + 8(double) + 4(int) ) = 20

So why it comes out be 24.

Also as you can see iam beginner can you provide some references where i can read more fundamental stuff or things which will be helpful.

I appreciate any advice you give. Thanks

  • 2
    20 is not a multiple of 8 (the number of bytes in a 64-bit word). – Robert Harvey Apr 09 '20 at 18:39
  • Imagine array of `Node`s. What would be the distance in bytes between two nodes? – KamilCuk Apr 09 '20 at 18:40
  • 1
    @Kerek AFAIK, all 64 bit machines still give `int` a 4 byte size and alignment. The issue here is the `double` needs an 8 byte alignment. – NathanOliver Apr 09 '20 at 18:58
  • DEV Awasthi, curious you padded `char` with 7 bytes to 8 (and not 3 bytes to 4), yet did not also pad the 4-byte `int` to 8. Why pad `char` to 8 and not also pad `int` to 8? – chux - Reinstate Monica Apr 09 '20 at 19:14
  • @chux-ReinstateMonica actually what i studied was in reference to memory cycle processor will do to read data so if i don't pad char by 7 bytes then processor will take 2 memory cycle to read data of double. But why i didn't padded int because i thought processor will read it in 1 cycle and will be over. – DEV Awasthi Apr 09 '20 at 19:22
  • Which language, C or C++? They are distinct languages. For example C++ may implement virtual function tables in a structure. For both languages, they are allowed to add padding between data members for alignment purposes or other purposes. – Thomas Matthews Apr 09 '20 at 19:52
  • @ThomasMatthews i am using C++. – DEV Awasthi Apr 09 '20 at 19:56
  • So, edit your language tags. – Thomas Matthews Apr 09 '20 at 19:57
  • @DEVAwasthi Makes sense. Yet consider if you had an array `Node a[2];` then since there is no padding between elements, the element itself needs the padding - a padding of 4 at the end to keep it all on an 8-byte boundary. – chux - Reinstate Monica Apr 09 '20 at 21:15
  • @DEVAwasthi You can always try to create a code to explain it to you, take [this code](https://godbolt.org/z/NbHf2c) as an example (notice that it may vary according to the compiler). – Kerek Apr 09 '20 at 21:54

0 Answers0