0

Have a look at following code:

#include<stdio.h>

struct Node
{
  int data;
  struct Node* nxt;
};

int main()
{
    int a = sizeof(struct Node);
    int b = sizeof(int);
    int c = sizeof(int*);

    printf("size of Node: %d\nsize of int: %d\nsize of int*: %d",a,b,c);

    return 0;
}

following is output of above code:

size of Node: 16
size of int: 4
size of int*: 8

my question is size of integer is 4 byte and size of integer pointer is 8 byte. So sum of these 2 should be size of struct. But why compiler (GCC) says it occupies 16 bytes?

geeksam
  • 33
  • 8

1 Answers1

1

[...] about structure padding. C compiler knows that storing unaligned data in RAM may be costly, so it pads your data for you. If you have 5 bytes of data in a structure, it will probably make it 8. Or 16. Or 6. Or whatever it wants. There are extensions like GCC attributes aligned and packed that let you get some control over this process, but they are non-standard. C itself does not define padding attributes, so the right answer is: “I don’t know”

https://hackernoon.com/so-you-think-you-know-c-8d4e2cd6f6a6

nicksheen
  • 550
  • 6
  • 23