0

My question is sizeof(char) is 1 byte but while executing below code why I am getting wrong output. Kindly help me. Thank you

typedef struct {

   int x;      
   int y;

   char a;

}Point2D;

main() {
   Point2D *myPoint=malloc(sizeof(Point2D));
   NSLog(@"sizeof(Point2D): %zu", sizeof(Point2D));
}

Output: sizeof(Point2D) : 12 //But it should return 9 [int + int + char / 4 + 4 + 1]

Note: While running char individually , I am getting correct output

Example:

typedef struct {

   char a;

   char b;

}Point2D;

main() {

   Point2D *myPoint=malloc(sizeof(Point2D));

   NSLog(@"sizeof(Point2D): %zu", sizeof(char));

}

output: sizeof(char) : 2

Nirav D
  • 71,513
  • 12
  • 161
  • 183
pgr
  • 23
  • 9
  • 1
    https://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member – Adam Wright Jun 19 '17 at 09:50
  • 1
    possible duplicate of https://stackoverflow.com/questions/1841863/size-of-struct-in-c – Aris Jun 19 '17 at 09:50

1 Answers1

2

You are not getting "wrong" output, when an (Objective-)C compiler lays out a struct it is allowed to use internal padding so that the fields start at the best memory alignment for their type.

If you need the size of a struct to be exactly the sum of its field sizes you can use __attribute__((__packed__)). E.g:

typedef struct
{
   int x;
   int y;
   char a;
} __attribute__((__packed__)) Point2D;

has a size of 9. However access to the fields may be slower due to the CPU having to deal with values not having optimal storage alignment.

CRD
  • 52,522
  • 5
  • 70
  • 86