我正试图获得内部结构的大小,即struct B.但我收到编译错误:
prog.c:在函数'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;
}
Run Code Online (Sandbox Code Playgroud)
您能否建议我如何在C中实现这一目标?
更新
来自@Jabberwocky的回答解决了我上面的问题.但是如何遵循代码呢.这也可以在这里找到:
#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;
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,我得到编译错误如下:
prog.c:8:8:错误:重新定义'struct
B'struct B
^
prog.c:5:10:注意:最初在这里定义
struct B {};
^
prog.c:在函数'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;
}
Run Code Online (Sandbox Code Playgroud)
工作样本:
#include <stdio.h>
struct A
{
int b;
struct B { int a; };
};
int main() {
printf("%d | %d", sizeof(struct A), sizeof(struct B));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
32位系统上可能的输出:
8 | 4
Run Code Online (Sandbox Code Playgroud)