【问题标题】:Getting wrong output while executing sizeof(char)执行 sizeof(char) 时输出错误
【发布时间】:2017-11-21 11:08:51
【问题描述】:

我的问题是 sizeof(char) 是 1 字节,但是在执行下面的代码时为什么我得到错误的输出。请帮助我。谢谢

typedef struct {

   int x;      
   int y;

   char a;

}Point2D;

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

输出:sizeof(Point2D) : 12 //但它应该返回 9 [int + int + char / 4 + 4 + 1]

注意:单独运行 char 时,我得到了正确的输出

例子:

typedef struct {

   char a;

   char b;

}Point2D;

main() {

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

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

}

输出:sizeof(char) : 2

【问题讨论】:

标签: ios objective-c xcode


【解决方案1】:

当(Objective-)C 编译器布置 struct 时,您不会得到“错误”的输出,它允许使用内部填充,以便字段从其类型的最佳内存对齐开始。

如果您需要struct 的大小恰好是其字段大小的总和,您可以使用__attribute__((__packed__))。例如:

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

大小为9。但是,由于 CPU 必须处理没有最佳存储对齐方式的值,访问字段可能会变慢。

【讨论】:

    猜你喜欢
    • 2022-12-18
    • 2017-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多