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

2

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.