我正在尝试获取内部结构的大小,即 struct B
。但是我遇到了编译错误:
prog.c: In function ‘main’: prog.c:10:53: error: expected ‘)’ before ‘:’ token printf("%d | %d", sizeof(struct A), sizeof(struct A::struct B));
以下是我的代码:
#include <stdio.h>
struct A
{
struct B{};
};
int main() {
printf("%d | %d", sizeof(struct A), sizeof(struct A::struct B));
return 0;
}
你能建议我如何在 C 中实现这个吗?
已更新
来自 @Jabberwocky 的回答解决了我的上述问题。但是下面的代码呢?这也可以找到here :
#include <stdio.h>
struct A
{
struct B{};
};
struct B
{};
int main() {
printf("%d | %d", sizeof(struct A), sizeof(struct B), sizeof(struct A::struct B));
return 0;
}
在这种情况下,我得到如下编译错误:
prog.c:8:8: error: redefinition of ‘struct B’
struct B
^
prog.c:5:10: note: originally defined here
struct B{};
^
prog.c: In function ‘main’:
prog.c:12:71: error: expected ‘)’ before ‘:’ token
printf("%d | %d", sizeof(struct A), sizeof(struct B), sizeof(struct A::struct B));
这里我如何区分 struct B
和 struct A::struct B
最佳答案
#include <stdio.h>
struct A
{
struct B{}; // this should not compile anyway in C as C
// does not allow empty structs
// but this would compile: struct B{int a;};
};
int main() {
printf("%d | %d", sizeof(struct A), sizeof(struct B));
// just write struct B
return 0;
}
工作样本:
#include <stdio.h>
struct A
{
int b;
struct B { int a; };
};
int main() {
printf("%d | %d", sizeof(struct A), sizeof(struct B));
return 0;
}
在 32 位系统上可能的输出:
8 | 4
关于c - 如何获取内部结构的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53336530/