【发布时间】:2015-01-08 11:40:44
【问题描述】:
我正在尝试以下操作,在 win32 上使用 gcc。
#include <stdio.h>
struct st { char c; int x; } __attribute__ ((packed));
int main() {
printf("%d\n", sizeof(struct st));
return 0;
}
我希望打印的值为 5,但它是 8。
但是,我得到 5。
#include <stdio.h>
#pragma pack(1)
struct st { char c; int x; };
int main() {
printf("%d\n", sizeof(struct st));
return 0;
}
我的程序一定有问题,但我看不出是什么。 我已经阅读了gcc's manual 和几个关于这个的问题,但我仍然感到困惑。有什么提示吗?
此外,从对 SO 的这些问题的回答中,我了解到我不应该对 marshalling 使用打包结构,而且我可能不会经常使用它,但我仍然想了解我无法做到的事情看到这么短的节目。
注意:gcc-4.9.2 和 gcc-4.8.4 都会出现问题。
【问题讨论】:
-
对我来说它有效。 codepad.org/Zrilgx9t
-
@Jayesh 好的,那么,我有来自mingw-w64 的 gcc-4.9.2,也许是这个版本的问题?
-
首先,你应该写 %lu 而不是 %d
-
@yakoudbz 这将在编译时抛出警告:
warning: format '%lu' expects argument of type 'long unsigned int', but argument 2 has type 'unsigned int'。但是,我同意 %d 应该由 %u 代替。当然也解决不了问题。 -
@Nivak 可能会也可能不会。但是你在这里寻找它gcc.gnu.org/bugzilla/show_bug.cgi?id=52991