-4
       typedef struct{
       short age;
       int money;
       char c; 
       }Persoana;   

       int main(void){
       Persoana *a = malloc(sizeof(Persoana));
       printf("%ld   %ld",sizeof(a->money),sizeof(a->age));
       printf("   %ld\n",sizeof(*a));   } ~

The code prints "4212".4 and 2 are ok but how so 12???

alk
  • 69,737
  • 10
  • 105
  • 255
Gabriel
  • 35
  • 1
  • 8
  • I'm voting to close this question as off-topic because it is non-constructive, as it has to do with the basics. – gsamaras Sep 07 '15 at 13:39
  • 1
    `sizeof()` needs `%zu`. – Sourav Ghosh Sep 07 '15 at 13:39
  • 6
    @gsamaras just being basic does not make a question off-topic. – Philipp Sep 07 '15 at 13:40
  • Oh that was from the auto-generated message, of course @Philipp! But still questions of this kind pollute SO IMHO. – gsamaras Sep 07 '15 at 13:41
  • 2
    @Philipp on general yeah, basic doesn't mean off-topic i agree but in this specific case , there's no problem and the OP made no effort, i am voting to close it also. – Kiloreux Sep 07 '15 at 13:41
  • 2
    The output does not suite the code. Please be more accurate. Accurate questions lead to accurate answers. – alk Sep 07 '15 at 13:42
  • 1
    @haris: Your edit is based on an assumption. I'd tend to roll this back. It's the OP's task to provide meaningful and accurate info. – alk Sep 07 '15 at 13:44
  • Ok i'm sorry,wont happen next time :) – Gabriel Sep 07 '15 at 13:45
  • 3
    Why not just clean up the mess now? – alk Sep 07 '15 at 13:46
  • 1
    And just to state this explicitly again: Questions *about* basics are very welcome at SO, as all well crafted questions are. SO isn't a closed, nerdish club. – alk Sep 07 '15 at 13:51

1 Answers1

6

It's to demonstrate padding issues done by the compiler. What it (the compiler) did here was to align each part of the struct to 4 byte word boundaries (=> 4*3 = 12 bytes) instead of packing them into 9 bytes. This is performed by the compiler to allow for data member access that respects the target CPU memory access patterns.

sansuiso
  • 9,259
  • 1
  • 40
  • 58